Python类
发布于 2017-09-19 · 本文总共 1008 字 · 阅读大约需要
3 分钟
调用父类方法-super
如何子类中调用父类的某个已经被覆盖的方法?
调用父类(超类)的一个方法,可以使用 super() 函数
class A:
def spam(self):
print('A.spam')
class B(A):
def spam(self):
print('B.spam')
super().spam() # Call parent spam()
super的其他两个使用场景
1.super() 函数的一个常见用法是在 init() 方法中确保父类被正确的初始化了
class Car(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class NewCar(Car):
def __init__(self,x, y,z, m, n):
super().__init__(x,y,z)
self.m = m
self.n = n
涉及到多继承, 错误示例:
Base.__init__被调用两次
MRO:
C.mro
class Base:
def __init__(self):
print('Base.__init__')
class A(Base):
def __init__(self):
Base.__init__(self)
print('A.__init__')
class B(Base):
def __init__(self):
Base.__init__(self)
print('B.__init__')
class C(A,B):
def __init__(self):
A.__init__(self)
B.__init__(self)
print('C.__init__')
2.覆盖Python特殊方法的
class NewProxy():
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value) # Call original __setattr__
else:
setattr(self._obj, name, value)