Python 继承与多态:方法重写与对象处理
1. 方法重写
在 Python 中,子类会继承父类的方法。若对继承的方法行为不满意,可在子类中指定新的实现来重写该方法。以 ChoiceQuestion 类的 display 方法为例,它重写了父类的 display 方法,用于显示答案选项。
class ChoiceQuestion(Question):
...
def display(self):
# Display the question text.
super().display()
# Display the answer choices.
for i in range(len(self._choices)):
choiceNumber = i + 1
print("%d: %s" % (choiceNumber, self._choices[i]))
这里使用 super() 函数调用父类的 display 方法来显示问题文本,因为父类的文本变量是私有的,不能直接访问。若使用 self.display() 会导致递归调用,因为 self 引用的是 ChoiceQuestion 对象,会不断调用当前正在编写的方法。
超级会员免费看
订阅专栏 解锁全文
802

被折叠的 条评论
为什么被折叠?



