类属性的继承
在课程前面,您已经学习了在一个类的所有实例之间共享的类属性和方法。那它们在继承时如何发挥作用呢?
在本练习中,您将基于本章前面使用过的 Player 类创建其子类,并探索类属性和方法的继承。
Player 类已为您定义,下面是提供的代码:
class Player:
MAX_POSITION = 10
def __init__(self):
self.position = 0
def move(self, steps):
if self.position + steps < Player.MAX_POSITION:
self.position += steps
else:
self.position = Player.MAX_POSITION
本练习是课程的一部分
Python 面向对象编程入门
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create a Racer class inheriting from Player
____(____):
# Create MAX_POSITION with a value of 15
____ = ____
# Create a Player and a Racer objects
p = ____
r = ____
print("p.MAX_POSITION = ", p.MAX_POSITION)
print("r.MAX_POSITION = ", r.MAX_POSITION)