在Python中,子类可以通过使用super()函数来调用父类的方法。super()函数返回一个临时对象,该对象允许你调用父类的方法。你可以通过在子类中使用super()函数来调用父类的方法,并提供必要的参数。
下面是一个示例:
class ParentClass: def __init__(self): self.name = "Parent" def say_hello(self): print("Hello from Parent")class ChildClass(ParentClass): def __init__(self): super().__init__() self.age = 10 def say_hello(self): super().say_hello() # 调用父类的say_hello方法 print("Hello from Child")child = ChildClass()child.say_hello()输出结果为:
Hello from ParentHello from Child 
