super().__init__() and the __dict__ method



当直接初始化继承的类而不是使用super().__init__()时,__dict__方法不会产生相同的结果。为什么?:

class A:
def __init__(self):
self.att_a = "A"    
class B:
def __init__(self):
self.att_b = "B"
class C(A, B):
def __init__(self):
A.__init__(self)
B.__init__(self)
self.att_c = "C"
def get_att(self):
print(self.__dict__) 
c = C()
c.get_att()

结果:{'attA': 'A', 'attB': 'B', 'attC': 'C'}

为什么使用super().__init__()不能产生相同的结果:

class A:
def __init__(self):
self.att_a = "A"    
class B:
def __init__(self):
self.att_b = "B"
class C(A, B):
def __init__(self):
super().__init__() # Modification
self.att_c = "C"
def get_att(self):
print(self.__dict__) 
c = C()
c.get_att()

结果:{'att_a': 'A', 'att_c': 'C'}

super().__init__只调用MRO中的next方法。A.__init__没有调用super().__init__,所以B.__init__永远不会被调用。

所有涉及的类都必须合作。

class A:
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.att_a = "A"    

class B:
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.att_b = "B"

class C(A, B):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.att_c = "C"
def get_att(self):
print(self.__dict__) 

# The MRO of C is [C, A, B, object]
# C.__init__ calls A.__init__
# A.__init__ calls B.__init__
# B.__init__ calls object.__init__
# object, as the root of the object hierarchy,
# does not use super().
c = C()
c.get_att()

在所有定义中添加**kwargs是为了容纳任何您可能不知道的扩展ABC的类。定义__init__的类不能提前知道super()接下来将调用什么类。

__init__()与MRO解析的任何其他方法一样,即只调用一个实现。多重继承只允许在所有子树中查找"right"方法定义:https://docs.python.org/3/library/functions.html#super

最新更新