2011-11-04 5 views
8

가능한 중복 :
Can Super deal with multiple inheritance?Super를 사용하여 여러 상위 클래스에 대해 init을 호출합니까?

파이썬 상속? 클래스 구조 (아래)가 있으며 하위 클래스에서 두 부모의 __init__을 호출하기를 원합니다. 이것은 '슈퍼'방식으로 할 수 있습니까 아니면 그냥 끔찍한 생각입니까?

class Parent1(object): 
    def __init__(self): 
     self.var1 = 1 

class Parent2(object): 
    def _init__(self): 
     self.var2 = 2 

class Child(Parent1, Parent2): 
    def __init__(self): 
     ## call __init__ of Parent1 
     ## call __init__ of Parent2 
     ## super(Child, self).__init__() 

답변

17

호출 super를 통해 모든 부모를 호출하지 않습니다, 그것은 MRO 체인의 다음 함수를 호출합니다. 이 제대로 작동하려면, 당신은 __init__의 모든에 super를 사용해야합니다 :

class Parent1(object): 
    def __init__(self): 
     super(Parent1, self).__init__() 
     self.var1 = 1 

class Parent2(object): 
    def __init__(self): 
     super(Parent2, self).__init__() 
     self.var2 = 2 

class Child(Parent1, Parent2): 
    def __init__(self): 
     super(Child, self).__init__() 

파이썬 3에서, 당신은 super() 대신 super(type, instance) 사용할 수 있습니다.

+0

다른 많은 질문과 답변을 읽었을 때 'super()'가 "MRO 체인의 다음 기능"을 호출하는 방법을 지적한 사람은 귀하뿐입니다. 참으로 간단하면서도 매우 중요한 성명서. – MikeyE

26

super()의 아이디어는 별도로 두 수퍼 클래스 '__init__() 메소드를 호출 귀찮게하지 않아도됩니다 - super()는 알아서 올바르게 사용 제공합니다 -에 대한 설명 Raymond Hettinger's "Python’s super() considered super!"를 참조하십시오.

그러나 저는 종종 생성자 호출이 장점을 능가하는 super()의 단점을 발견했습니다. 예를 들어 모든 생성자는 **kwargs 인수를 추가로 제공해야하며 모든 클래스가 공동 작업해야하며 외부 클래스에 래퍼가 필요합니다. 각 생성자 매개 변수 이름은 모두 클래스 등에서 고유해야합니다.

class Child(Parent1, Parent2): 
    def __init__(self): 
     Parent1.__init__(self) 
     Parent2.__init__(self) 

내가 __getattr__()처럼 보장 된 프로토 타입이 기능 super()을 사용합니까 :

그래서 더 자주 못하는 것보다, 나는 명시 적으로 생성자 호출 할 기본 클래스 메서드 호출의 이름을 쉽게 생각 그래도. 이 경우에는 단점이 없습니다.

7

그냥 Parent.__init__(self)로 직접 호출 할 수 있습니다

class Parent1(object): 
    def __init__(self): 
        self.var1 = 1 

class Parent2(object): 
    def _init__(self): 
        self.var2 = 2 

class Child(Parent1, Parent2): 
    def __init__(self): 
     Parent1.__init__(self) 
     Parent2.__init__(self)