类的继承和实现原理
1.类的继承实例
class Hero: aa = '11' def __init__(self, name, life, damage): self.name = name self.life = life self.damage = damage def attack(self, enemy): enemy.life -= self.damage class Hero1(Hero): pass st1 = Hero1('gaohui', '100', 50) print(st1.__dict__) print(Hero1.__bases__) print(st1.aa) 输出结果为: {'name': 'gaohui', 'life': '100', 'damage': 50} (<class '__main__.Hero'>,) 11
类的继承中一个易错点
当父类和子类中有相同的方法时,谁的对象调就是谁的方法
class Foo: def f1(self): print('from Foo.f1') def f2(self): print('from Foo.f2') self.f1() # 哪个对象调就是对象的f1 ,所以这个方法就是b的f1 class Bar(Foo): def f1(self): print('from Bar.f2') b = Bar() b.f2() 输出结果: from Foo.f2 from Bar.f2
继承的实现原理
当类是新式类时,在多继承时,查找的属性不存在时,会按广度优先(即不会先找到父类)去找。
class A(object): def test(self): print('from A') class B(A): def test(self): print('from B') class C(A): def test(self): print('from C') class D(B): def test(self): print('from D') class E(C): def test(self): print('from E') class F(D, E): pass print(F.mro()) # 得出广度优先选择的顺序 结果 [<class '__main__.F'>, <class '__main__.D'>, <class '__main__.B'>, <class '__main__.E'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]