python继承
多继承
- 有相同的祖先
class Base: def test(self): print("----Base") class A(Base): pass # def test(self): # print("-----A") class B(Base): def test(self): print("-----B") class C(A,B): pass c = C() c.test() #调用方法查找顺序 类名.__mro__ print(C.__mro__) 结果: -----B (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.Base'>, <class 'object'>)
- 有不同的祖先:
class Base: def test(self): print("----Base") class Base2: def test(self): print("----Base2") class A(Base): def test(self): print("-----A") class B(Base2): def test(self): print("-----B") class C(A,B): pass c = C() c.test() #调用方法查找顺序 类名.__mro__ print(C.__mro__) 结果: -----A (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.Base'>, <class '__main__.B'>, <class '__main__.Base2'>, <class 'object'>)
调用被重写的父类的方法
1 class Person: 2 def eat(self): 3 print("---person eating---") 4 5 class Man(Person): 6 def eat(self): 7 #调用被重写的父类的方法 8 #第一种方法 9 Person.eat(self) 10 #第二种方法 11 super().eat() 12 print("---man eating---") 13 14 h = Man() 15 h.eat()