推荐答案
在 Python 中,调用父类的方法可以通过 super() 函数来实现。super() 函数返回一个临时对象,该对象允许你调用父类的方法。以下是调用父类方法的示例代码:
// www.javascriptcn.com code example
class Parent:
def __init__(self):
self.value = 5
def display(self):
print("Value from Parent:", self.value)
class Child(Parent):
def __init__(self):
super().__init__() # 调用父类的 __init__ 方法
self.child_value = 10
def display(self):
super().display() # 调用父类的 display 方法
print("Value from Child:", self.child_value)
# 创建 Child 类的实例
child = Child()
child.display()输出结果:
Value from Parent: 5 Value from Child: 10
本题详细解读
1. super() 函数的作用
super() 函数用于调用父类的方法。它返回一个代理对象,该对象将方法调用委托给父类。super() 通常用于以下场景:
- 在子类的
__init__方法中调用父类的__init__方法,以确保父类的初始化逻辑被执行。 - 在子类中重写父类的方法时,仍然希望保留父类的行为。
2. super() 的使用方式
单继承:在单继承的情况下,
super()可以直接调用父类的方法。例如:super().__init__()
这行代码会调用父类的
__init__方法。多继承:在多继承的情况下,
super()会根据方法解析顺序(MRO)来决定调用哪个父类的方法。MRO 是 Python 用来确定方法调用顺序的算法,通常使用 C3 线性化算法。
3. 注意事项
- 在 Python 3 中,
super()不需要显式传递子类和实例,它会自动推断出当前的类和实例。 - 在 Python 2 中,
super()需要显式传递子类和实例,例如:super(Child, self).__init__()。
4. 示例代码解析
在示例代码中,Child 类继承自 Parent 类。Child 类的 __init__ 方法中调用了 super().__init__(),这确保了 Parent 类的 __init__ 方法被调用,从而初始化了 self.value。
在 Child 类的 display 方法中,super().display() 调用了 Parent 类的 display 方法,输出了 self.value 的值。然后,Child 类的 display 方法继续输出 self.child_value 的值。
通过这种方式,子类可以在保留父类行为的基础上,添加或修改自己的逻辑。