直接调用父类的super方法
class A:
def span(self):
print('---a---')
class B(A):
def span(self):
print('-----b-----')
super().span()
b = B()
print(b.span())
调用父类的init()方法,确保父类被正确初始化
class C:
def __init__(self):
self.x = 1
class D(C):
def __init__(self):
super().__init__()
self.y = 1
d = D()
print(d.x, d.y)
当覆盖了python中的特殊方法时
class Proxy:
def __init__(self, obj):
self.obj = obj
def __getattr__(self, name):
return getattr(self._obj, name)
def __setattr__(self, name, value):
if name.startswith("_"):
# __setattr__方法被覆盖,调用父类的原始方法
super().__setattr__(name, value)
else:
setattr(self._obj, name, value)