查看 Python 类的继承体系
查看 datetime.date
的继承体系
>>> import datetime
>>> datetime.date.__mro__
Out:
(datetime.date, object)
查看 datetime.datetime
的继承体系
>>> datetime.datetime.__mro__
Out:
(datetime.datetime, datetime.date, object)
多重继承
两个有相同方法名的类:
class AboutMROA:
def common_func(self):
print("call me at: ", "AboutMROA")
class AboutMROB:
def common_func(self):
print("call me at: ", "AboutMROB")
继承顺序
先 A 后 B
多重继承,与顺序,调用父类方法:
class OrderFirstAThenB(AboutMROA, AboutMROB):
def common_func(self):
print("call me at: ", 'OrderFirstAThenB')
super().common_func()
检查 MRO:
>>> OrderFirstAThenB.__mro__
Out:
(__main__.OrderFirstAThenB, __main__.AboutMROA, __main__.AboutMROB, object)
调用这个方法执行的逻辑:
>>> OrderFirstAThenB().common_func()
Out:
call me at: OrderFirstAThenB call me at: AboutMROA
先 B 后 A
class OrderFirstBThenA(AboutMROB, AboutMROA):
def common_func(self):
print("call me at: ", 'OrderFirstBThenA')
super().common_func()
>>> OrderFirstBThenA.__mro__
(__main__.OrderFirstBThenA, __main__.AboutMROB, __main__.AboutMROA, object)
>>> OrderFirstBThenA().common_func()
call me at: OrderFirstBThenA
call me at: AboutMROB
相同的方法名,会按照 MRO 规则,找到第一个类里面的该方法,然后执行,如果多重继承后面的类也有改方法,其实是等效于被靠前的类中改方法覆盖/重写了这个方法