Repository navigation
Expand file tree
/
Copy path09_classes_and_objects.py
More file actions
145 lines (112 loc) · 5.33 KB
/
Copy path09_classes_and_objects.py
File metadata and controls
145 lines (112 loc) · 5.33 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# -*- coding: utf-8 -*-
# --- 第9章:类与对象 (面向对象编程基础) ---
# 面向对象编程 (Object-Oriented Programming, OOP) 是一种编程范式,
# 它将数据和操作数据的方法封装在一起,形成“对象”。
# 类是创建对象的蓝图或模板,对象是类的实例。
# --- 1. 定义类 (Class) ---
# 使用 class 关键字定义类。类名通常使用驼峰命名法 (CamelCase)。
class Dog:
"""这是一个表示狗的类。"""
# 类属性:所有实例共享的属性
species = "Canis familiaris"
# 构造函数 (Constructor): __init__ 方法
# 当创建类的新实例时,会自动调用此方法。
# self 参数是对实例本身的引用,必须是方法的第一个参数。
def __init__(self, name, age):
# 实例属性:每个实例独有的属性
self.name = name
self.age = age
# 实例方法:操作实例属性的函数
def bark(self):
"""狗叫的方法。"""
print(f"{self.name} says Woof!")
def get_age_in_human_years(self):
"""计算狗的年龄相当于人类的年龄。"""
return self.age * 7
# --- 2. 创建对象 (Object / Instance) ---
# 通过调用类名来创建类的实例。
my_dog = Dog("Buddy", 3) # 创建 Dog 类的实例 my_dog
your_dog = Dog("Lucy", 5) # 创建 Dog 类的另一个实例 your_dog
# --- 3. 访问属性 ---
# 使用点号 (.) 来访问对象的属性。
print("--- 访问属性示例 ---")
print(f"我的狗的名字是: {my_dog.name}")
print(f"我的狗的年龄是: {my_dog.age}")
print(f"我的狗的物种是: {my_dog.species}") # 访问类属性
print(f"你的狗的名字是: {your_dog.name}")
print(f"你的狗的年龄是: {your_dog.age}")
# --- 4. 调用方法 ---
# 使用点号 (.) 来调用对象的方法。
print("\n--- 调用方法示例 ---")
my_dog.bark()
your_dog.bark()
print(f"{my_dog.name} 的人类年龄是: {my_dog.get_age_in_human_years()} 岁")
# --- 5. 继承 (Inheritance) ---
# 继承允许一个类 (子类/派生类) 继承另一个类 (父类/基类) 的属性和方法。
# 子类可以添加新的属性和方法,也可以重写父类的方法。
class GoldenRetriever(Dog):
"""金毛寻回犬类,继承自 Dog 类。"""
def __init__(self, name, age, color):
# 调用父类的构造函数来初始化父类的属性
super().__init__(name, age)
self.color = color # 金毛特有的属性
# 重写父类的方法
def bark(self):
print(f"{self.name} says Woof woof! (friendly bark)")
# 子类特有的方法
def retrieve(self, item):
print(f"{self.name} is retrieving the {item}.")
print("\n--- 继承示例 ---")
my_golden = GoldenRetriever("Max", 2, "golden")
print(f"我的金毛的名字是: {my_golden.name}")
print(f"我的金毛的颜色是: {my_golden.color}")
my_golden.bark() # 调用重写后的 bark 方法
my_golden.retrieve("ball") # 调用子类特有的方法
print(f"我的金毛的物种是: {my_golden.species}") # 继承自父类的类属性
# --- 6. 多态 (Polymorphism) ---
# 多态是指不同类的对象可以对同一个方法调用做出不同的响应。
# 在 Python 中,多态是自然发生的,因为 Python 是动态类型语言。
print("\n--- 多态示例 ---")
def make_animal_bark(animal):
animal.bark()
make_animal_bark(my_dog) # 调用 Dog 类的 bark 方法
make_animal_bark(my_golden) # 调用 GoldenRetriever 类的 bark 方法
# --- 7. 封装 (Encapsulation) ---
# 封装是将数据(属性)和操作数据的方法(函数)捆绑在一起的机制。
# Python 没有严格的访问修饰符(如 public, private),但约定俗成地使用:
# - 单下划线前缀 (_name): 表示受保护的成员,建议不要直接访问。
# - 双下划线前缀 (__name): 表示私有成员,Python 会进行名称修饰 (name mangling),使其更难被外部直接访问。
class BankAccount:
def __init__(self, balance):
self.__balance = balance # 私有属性,不建议直接访问
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"存款 {amount} 成功。当前余额: {self.__balance}")
else:
print("存款金额必须大于0。")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"取款 {amount} 成功。当前余额: {self.__balance}")
else:
print("取款金额无效或余额不足。")
def get_balance(self):
return self.__balance
print("\n--- 封装示例 ---")
my_account = BankAccount(1000)
my_account.deposit(500)
my_account.withdraw(200)
my_account.withdraw(2000) # 余额不足
print(f"账户当前余额: {my_account.get_balance()}")
# print(my_account.__balance) # 这行会报错,因为 __balance 是私有属性
# --- 章节总结 ---
# 1. 类 (Class): 对象的蓝图,用 class 关键字定义。
# 2. 对象 (Object/Instance): 类的具体实例。
# 3. __init__: 构造函数,用于初始化对象属性。
# 4. self: 指向当前实例的引用。
# 5. 属性: 对象的特征 (类属性和实例属性)。
# 6. 方法: 对象可以执行的动作。
# 7. 继承: 子类继承父类的属性和方法。
# 8. 多态: 不同对象对同一方法调用做出不同响应。
# 9. 封装: 将数据和方法捆绑在一起,控制访问。