python面向对象学习
时间: 2023-11-21 14:57:59 浏览: 86
Python是一种面向对象的编程语言,它支持面向对象编程(OOP)的所有基本概念,例如类、对象、继承、封装和多态性。下面是Python面向对象编程的一些基本概念和示例:
1.定义一个类
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old.")
# 创建对象实例
person = Person("Alice", 25)
person.say_hello() # 输出:Hello, my name is Alice and I am 25 years old.
```
2.继承一个类
```python
class Student(Person):
def __init__(self, name, age, grade):
super().__init__(name, age)
self.grade = grade
def say_hello(self):
print("Hello, my name is", self.name, "and I am a student in grade", self.grade)
# 创建对象实例
student = Student("Bob", 18, 12)
student.say_hello() # 输出:Hello, my name is Bob and I am a student in grade 12.
```
3.封装一个类
```python
class BankAccount:
def __init__(self, balance):
self.__balance = balance
def deposit(self, amount):
self.__balance += amount
def withdraw(self, amount):
if amount > self.__balance:
print("Insufficient funds")
else:
self.__balance -= amount
def get_balance(self):
return self.__balance
# 创建对象实例
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # 输出:1300
```
阅读全文