python 基础——多重继承
原始的初始化
子类直接调用超类 __init__ 方法初始化,当形成钻石继承的时候,超类会被多次初始化,可能会有意向不到的问题:
BaseClass
/ \
OneClass TwoClass
\ /
TestClass
from pprint import pprint class BaseClass(object): def __init__(self, a): # value = a self.value = a class OneClass(BaseClass): def __init__(self, a): BaseClass.__init__(self, a) # value + 2 self.value += 2 class TwoClass(BaseClass): def __init__(self, a): BaseClass.__init__(self, a) # value * 2 self.value *= 2 class TestClass(TwoClass, OneClass): def __init__(self, a): TwoClass.__init__(self, a) OneClass.__init__(self, a) # value + 8 self.value += 8 print self.value pprint(TestClass.mro()) test = TestClass(3) # 13 # 初始化的过程是:BaseClass ——> TwoClass ——> BaseClass ——> OneClass ——> TestClass # value 的变化: value = 3 ——> value = 6 ——> value = 3 ——> value = 5 ——> value = 13
新类初始化
使用 super 可以解决超类重复初始化的问题,保证超类只被初始化一次:
from pprint import pprint class BaseClass(object): def __init__(self, a): # value = a self.value = a class OneClass(BaseClass): def __init__(self, a): super(OneClass, self).__init__(a) # value + 2 self.value += 2 class TwoClass(BaseClass): def __init__(self, a): super(TwoClass, self).__init__(a) # value * 2 self.value *= 2 class TestClass(TwoClass, OneClass): def __init__(self, a): super(TestClass, self).__init__(a) # value + 8 self.value += 8 print self.value pprint(TestClass.mro()) """ 以以下相反的顺序初始化子类 [<class 'TestClass'>, <class 'TwoClass'>, <class 'OneClass'>, <class 'BaseClass'>, <type 'object'>] """ test = TestClass(3) # 18 # 初始化的过程是:BaseClass ——> OneClass ——> TwoClass ——> TestClass # value 的变化: value = 3 ——> value = 5 ——> value = 10 ——> value = 18