2017-05-13 4 views

답변

6

super()는 MRO 순서에서 다음 방법을 찾을 수 있습니다 :

class B(): 
    def __init__(self): 
     print("__init__ of B called") 
     self.b = "B" 

class C(): 
    def __init__(self): 
     print("__init__ of C called") 
     self.c = "C" 

class D(B, C): 
    def __init__(self): 
     print("__init__ of D called") 
     super().__init__() 

    def output(self): 
     print(self.b, self.c) 

d = D() 
d.output() 

나는 다음과 같은 오류를 얻고있다. 즉 기본 클래스에서 __init__ 개의 메소드 중 하나만 호출하게됩니다.

당신은 클래스의 __mro__ attribute보고하여 MRO합니다 (방법 해상도 ​​주문을) 검사 할 수 있습니다 :

>>> D.__mro__ 
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>) 

그렇게 D에서, 다음 클래스는 Cobject 다음, B입니다. D.__init__()에서 super().__init__() 식은 B.__init__()만을 호출하고 C.__init__()이 아니기 때문에이라고하지 않으므로 self.c도 설정되지 않습니다.

클래스 구현에 super() 개의 호출을 추가해야합니다.

>>> d = D() 
__init__ of D called 
__init__ of B called 
__init__ of C called 
>>> d.output() 
B C 
: D().output() 작품을 호출

이제 B.__init__
class B(): 
    def __init__(self): 
     print("__init__ of B called") 
     super().__init__() 
     self.b = "B" 

class C(): 
    def __init__(self): 
     print("__init__ of C called") 
     super().__init__() 
     self.c = "C" 

class D(B, C): 
    def __init__(self): 
     print("__init__ of D called") 
     super().__init__() 

    def output(self): 
     print(self.b, self.c) 

C.__init__를 호출하고, C.__init__object.__init__를 호출하고 : 그냥 여기 모든 곳에서 그들에게를 사용하므로, 인수없이 object.__init__()를 호출하는 것이 안전합니다