Python 基础:面向对象
4.1 类与对象
python
class Person:
"""人类"""
# 类属性(所有实例共享)
species = "Human"
# 构造函数
def __init__(self, name: str, age: int):
self.name = name # 实例属性
self.age = age
# 实例方法
def greet(self):
return f"我叫{self.name},今年{self.age}岁"
# 字符串表示
def __str__(self):
return f"Person({self.name}, {self.age})"
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
# 创建实例
p = Person("Alice", 25)
print(p.greet()) # 我叫Alice,今年25岁
print(p.species) # Human
print(str(p)) # Person(Alice, 25)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
4.2 继承
python
class Student(Person):
"""学生类,继承自 Person"""
def __init__(self, name: str, age: int, grade: int):
super().__init__(name, age) # 调用父类构造函数
self.grade = grade # 新增属性
# 方法重写
def greet(self):
return f"我是学生{self.name},读{self.grade}年级"
# 新增方法
def study(self, subject: str):
return f"{self.name}正在学习{subject}"
s = Student("Bob", 15, 9)
print(s.greet()) # 我是学生Bob,读9年级
print(s.study("数学")) # Bob正在学习数学1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
4.3 封装(私有属性)
python
class BankAccount:
"""银行账户"""
def __init__(self, balance: float):
self.__balance = balance # 私有属性(双下划线开头)
def deposit(self, amount: float):
if amount <= 0:
raise ValueError("存款金额必须为正")
self.__balance += amount
def withdraw(self, amount: float):
if amount > self.__balance:
raise ValueError("余额不足")
self.__balance -= amount
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# print(account.__balance) # AttributeError: 访问不到私有属性1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
4.4 多态
python
class Animal:
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "汪汪!"
class Cat(Animal):
def speak(self):
return "喵喵!"
class Duck(Animal):
def speak(self):
return "嘎嘎!"
# 多态:同一接口,不同实现
animals = [Dog(), Cat(), Duck()]
for animal in animals:
print(animal.speak())1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
4.5 @property 装饰器
python
class Circle:
def __init__(self, radius: float):
self.__radius = radius
@property
def radius(self):
"""获取半径"""
return self.__radius
@radius.setter
def radius(self, value: float):
if value < 0:
raise ValueError("半径不能为负")
self.__radius = value
@property
def area(self):
"""计算面积(只读属性)"""
return 3.14159 * self.__radius ** 2
c = Circle(5)
print(c.radius) # 5(像访问属性一样)
print(c.area) # 78.54(只读)
c.radius = 10 # 通过 setter 设置1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[[返回 Python 首页|python/index]]