1
저는 python을 처음 사용합니다. 파이썬 다중 상속에서 super()
기능을 이해하려고합니다.python의 다중 상속에서 super() 사용
AttributeError: 'D' object has no attribute 'c'
저는 python을 처음 사용합니다. 파이썬 다중 상속에서 super()
기능을 이해하려고합니다.python의 다중 상속에서 super() 사용
AttributeError: 'D' object has no attribute 'c'
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
에서, 다음 클래스는 C
및 object
다음, 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__()
를 호출하는 것이 안전합니다