class MyBaseClass:
def __init__(self, value):
self.value = value
__init__
方法__init__
方法的先后顺序class MyChildClass(MyBaseClass):
def __init__(self):
MyBaseClass.__init__(self, 5)
class TimesTwo:
def __init__(self):
self.value *= 2
class PlusFive:
def __init__(self):
self.value += 5
class OneWay(MyBaseClass, TimesTwo, PlusFive):
def __init__(self, value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
foo = OneWay(5)
print(foo.value)
输出
15
class AnotherWay(MyBaseClass, PlusFive, TimesTwo):
def __init__(self, value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)
bar = AnotherWay(5)
print(bar.value)
输出
15
PlusTwo.__init__(self, value)
会重新调用 MyBaseClass.__int__
,从而导致 self.value
重新变为 5class TimesFive(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value *= 5
class PlusTwo(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value += 2
class ThisWay(TimesFive, PlusTwo):
def __init__(self, value):
TimesFive.__init__(self, value)
PlusTwo.__init__(self, value)
foo = ThisWay(5)
print(foo.value)
输出
7
super
初始化超类TimesFiveCorrect.__init__
,PlusTwoCorrect.__init__
,MyBaseClass.__init__
即 (5+2)*5 = 35super
所在的类 和 self
对象,而且还要指定相关的方法名称 __init__
class TimesFiveCorrect(MyBaseClass):
def __init__(self, value):
super(TimesFiveCorrect, self).__init__(value)
self.value *= 5
class PlusTwoCorrect(MyBaseClass):
def __init__(self, value):
super(PlusTwoCorrect, self).__init__(value)
self.value += 2
class GoodWay(TimesFiveCorrect, PlusTwoCorrect):
def __init__(self, value):
super(GoodWay, self).__init__(value)
foo = GoodWay(5)
print(foo.value)
print(GoodWay.mro())
输出
35
[<class '__main__.GoodWay'>, <class '__main__.TimesFiveCorrect'>, <class '__main__.PlusTwoCorrect'>, <class '__main__.MyBaseClass'>, <class 'object'>]
__class__
替代指定当前类class GoodWay3(TimesFiveCorrect, PlusTwoCorrect):
def __init__(self, value):
super().__init__(value)
foo = GoodWay2(5)
print(foo.value)
输出
35
class GoodWay3(TimesFiveCorrect, PlusTwoCorrect):
def __init__(self, value):
super().__init__(value)
foo = GoodWay3(5)
print(foo.value)
输出
35