在Python中,子类调用父类方法主要有以下三种方式,具体使用需根据场景选择:
一、使用super()
函数(推荐)
super()
是Python 3中推荐的方式,用于调用父类方法,支持动态绑定,代码更简洁易维护。
-
调用父类方法
class Parent: def method(self): print("Parent method") class Child(Parent): def method(self): super().method() # 调用父类方法 print("Child method")
-
调用父类构造函数
class Parent: def __init__(self): print("Parent init") class Child(Parent): def __init__(self): super().__init__() # 调用父类构造函数 print("Child init")
二、直接使用父类名称调用
适用于Python 2或需要显式指定父类名的场景,但代码可读性较差,且父类名变化时需修改子类代码。
class Parent:
def method(self):
print("Parent method")
class Child(Parent):
def method(self):
Parent.method(self) # 直接调用父类方法
print("Child method")
三、使用super(type, self)
(兼容Python 2)
在Python 2中,super()
需显式传递父类和实例,但Python 3已统一使用super()
简化语法。
class Parent:
def method(self):
print("Parent method")
class Child(Parent):
def method(self):
super(Parent, self).method() # 兼容Python 2的调用方式
print("Child method")
注意事项
-
必须调用父类构造函数 :若子类未调用父类构造函数(如
super().__init__()
),子类实例将无法访问父类属性。 -
避免直接使用类名 :直接调用类名(如
Parent.method(self)
)在父类名变化时易出错,推荐使用super()
。
通过以上方式,子类可灵活调用父类方法,同时保持代码的可维护性。