一、什么是实例属性和实例方法?
在面向对象编程中,实例属性 和 实例方法 是属于对象个体的成员:
- • 实例属性:存储对象特有的数据。每个对象都有自己的属性值,互不影响。
- • 实例方法:定义对象的行为。方法中的
self 参数指向调用该方法的对象本身,因此可以访问该对象的属性。
classDog:
def__init__(self, name, age):
self.name = name # 实例属性
self.age = age # 实例属性
defbark(self): # 实例方法
print(f"{self.name} 在汪汪叫")
dog1 = Dog("旺财", 3)
dog2 = Dog("小黑", 2)
print(dog1.name) # 旺财
print(dog2.name) # 小黑(不同对象,属性值独立)
dog1.bark() # 旺财 在汪汪叫
二、实例属性详解
2.1 定义实例属性
实例属性通常在 __init__ 方法中通过 self.属性名 = 值 定义。
classStudent:
def__init__(self, name, score):
self.name = name # 定义实例属性
self.score = score
self.grade = "未评级"# 可以设置固定初始值
也可以在 __init__ 之外的实例方法中定义,但不推荐,因为可能导致属性不存在的风险。
2.2 访问实例属性
通过 对象.属性名 访问。
s = Student("小明", 85)
print(s.name) # 小明
print(s.score) # 85
2.3 修改实例属性
直接赋值即可修改。
s.score = 90
print(s.score) # 90
2.4 动态添加实例属性
Python 是动态语言,允许在对象创建后动态添加新的实例属性。
s.city = "北京"# 动态添加属性
print(s.city) # 北京
虽然灵活,但滥用会使代码难以维护。建议在 __init__ 中预先定义所有合理的属性。
2.5 删除实例属性
使用 del 语句可以删除实例属性。
del s.city
# print(s.city) # AttributeError
三、实例方法详解
3.1 定义实例方法
实例方法的第一个参数必须是 self,代表调用该方法的对象本身。
classCalculator:
defadd(self, a, b): # 实例方法
return a + b
defmultiply(self, a, b):
return a * b
3.2 调用实例方法
通过 对象.方法名(参数) 调用。Python 会自动将对象作为 self 传入。
calc = Calculator()
result = calc.add(3, 5) # 等价于 Calculator.add(calc, 3, 5)
print(result) # 8
3.3 在实例方法中访问实例属性
通过 self.属性名 可以访问当前对象的属性。
classCircle:
def__init__(self, radius):
self.radius = radius
defarea(self):
return3.14 * self.radius * self.radius # 使用 self.radius
defperimeter(self):
return2 * 3.14 * self.radius
c = Circle(5)
print(c.area()) # 78.5
print(c.perimeter()) # 31.400000000000002
3.4 在实例方法中调用其他实例方法
通过 self.方法名() 调用同一实例的其他方法。
classRectangle:
def__init__(self, width, height):
self.width = width
self.height = height
defarea(self):
returnself.width * self.height
defperimeter(self):
return2 * (self.width + self.height)
definfo(self):
area = self.area() # 调用实例方法
perimeter = self.perimeter()
print(f"面积: {area}, 周长: {perimeter}")
rect = Rectangle(4, 5)
rect.info() # 面积: 20, 周长: 18
四、类属性与类方法(对比)
| | | |
| self.attr = value | 对象.attr | |
| attr = value | 类.attr | |
| def method(self): | 对象.method() | |
| @classmethod | 类.method() | |
classExample:
class_attr = 100# 类属性
def__init__(self, value):
self.instance_attr = value # 实例属性
definstance_method(self):
print("实例方法")
@classmethod
defclass_method(cls):
print("类方法")
五、实战案例
5.1 银行账户类
classBankAccount:
def__init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self._transaction_history = [] # 以下划线开头表示“保护”属性
defdeposit(self, amount):
if amount > 0:
self.balance += amount
self._record_transaction(f"存款 +{amount}")
returnTrue
returnFalse
defwithdraw(self, amount):
if0 < amount <= self.balance:
self.balance -= amount
self._record_transaction(f"取款 -{amount}")
returnTrue
returnFalse
def_record_transaction(self, record):
"""内部方法,以下划线开头表示“内部使用”"""
self._transaction_history.append(record)
defshow_history(self):
for record inself._transaction_history:
print(record)
# 使用
acc = BankAccount("张三", 1000)
acc.deposit(500)
acc.withdraw(200)
acc.show_history()
# 存款 +500
# 取款 -200
5.2 学生成绩管理
classStudent:
def__init__(self, name, scores=None):
self.name = name
self.scores = scores if scores isnotNoneelse []
defadd_score(self, score):
if0 <= score <= 100:
self.scores.append(score)
else:
print("成绩无效")
defaverage(self):
ifnotself.scores:
return0
returnsum(self.scores) / len(self.scores)
defhighest(self):
ifnotself.scores:
returnNone
returnmax(self.scores)
definfo(self):
print(f"学生: {self.name}")
print(f"成绩: {self.scores}")
print(f"平均分: {self.average():.2f}")
print(f"最高分: {self.highest()}")
s = Student("小明")
s.add_score(85)
s.add_score(92)
s.add_score(78)
s.info()
5.3 计数器类
classCounter:
def__init__(self):
self._count = 0
defincrement(self):
self._count += 1
returnself._count
defdecrement(self):
self._count -= 1
returnself._count
defreset(self):
self._count = 0
defget_count(self):
returnself._count
c = Counter()
c.increment()
c.increment()
print(c.get_count()) # 2
c.decrement()
print(c.get_count()) # 1
六、常见错误与注意事项
6.1 在实例方法中忘记写 self
classTest:
defmethod(): # 错误:缺少 self 参数
print("hello")
6.2 调用方法时忘记括号
obj.method # 这只是引用方法对象,不会执行
obj.method() # 正确:执行方法
6.3 类属性与实例属性同名导致混淆
classDemo:
value = 100# 类属性
def__init__(self):
self.value = 200# 实例属性,覆盖了同名的类属性
访问时,实例属性优先于类属性。
6.4 在类内部使用 类名 而不是 self 访问实例属性
classWrong:
def__init__(self, name):
self.name = name
defshow(self):
print(name) # 错误:应该是 self.name
6.5 动态添加属性导致维护困难
尽量避免在 __init__ 外部动态添加属性,这会让代码逻辑难以追踪。
七、总结
- • 实例属性:属于每个对象个体,存储对象特有的数据。在
__init__ 中通过 self.attr = value 定义。 - • 实例方法:定义对象的行为,第一个参数必须是
self,通过 对象.method() 调用。 - • 在实例方法内部,通过
self.attr 访问实例属性,通过 self.method() 调用其他实例方法。 - • Python 允许动态添加/删除实例属性,但应谨慎使用。
- • 合理组织实例属性和方法,是实现良好封装和代码复用的基础。
掌握实例属性和实例方法,是面向对象编程的核心技能之一。它们让每个对象能够拥有自己的状态和行为,真正体现了“对象”的含义。