修改类属性
您已经学会如何定义类属性,以及如何从类的实例访问它们。那么,当您从实例访问类属性时,若尝试为它重新赋值,会发生什么?
上一练习中的 Player 类已预先定义,如下所示:
class Player:
MAX_POSITION = 10
def __init__(self, position):
if position <= Player.MAX_POSITION:
self.position = position
else:
self.position = Player.MAX_POSITION
本练习是课程的一部分
Python 面向对象编程入门
练习说明
- 创建两个
Player对象:p1和p2,位置分别为9和5。 - 打印
p1.MAX_POSITION和p2.MAX_POSITION。 - 将
7赋给p1.MAX_POSITION。 - 再次打印
p1.MAX_POSITION和p2.MAX_POSITION。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create Players p1 and p2
p1 = ____
p2 = ____
print("MAX_POSITION of p1 and p2 before assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____
# Assign 7 to p1.MAX_POSITION
____
print("MAX_POSITION of p1 and p2 after assignment:")
# Print p1.MAX_POSITION and p2.MAX_POSITION
____
____