一、单继承
子类调用父类的一个方法,可以用super():
class A(object): def pp(self): print('pp A') class B(A): def pp(self): super().pp() print("pp B")
b = B()b.pp()#结果:
pp A pp B
super()常用的方法是在__init__()方法中确保父类被正确的初始化了:
super(cls,inst).__init__() #cls,init 可以省略
class A(object): def __init__(self): self.x = 1 class B(A): def __init__(self): super(B,self).__init__() self.x = self.x +1 print(self.x) b = B()#结果2
也可以直接调用父类的一个方法 :
A.__init__(self)
class A(object): def __init__(self): self.x = 1 class B(A): def __init__(self): A.__init__(self) self.x = self.x +1 print(self.x) b = B()#结果2
二、多继承