1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Base(object): def __init__(self): print("Base created") class ChildA(Base): def __init__(self): Base.__init__(self) print("childA") class ChildB(Base): def __init__(self): super(ChildB, self).__init__() print("childB") class ChildC(Base): def __init__(self): super().__init__() print("childC") ChildA() ChildB() ChildC() | cs
|
|
| 결과 : Base created
childA
Base created
childB
Base created
childC
|
|
지금 위 코드를 보면 클래스 ChildA, ChildB, ChildC는 Base class를 상속 받는다.
그리고 각 __init__ 함수는 각 클래스의 이름을 출력한다.
여기서 super()를 이용해서 부모 클래스의 초기화 함수를 호출할 수 있다.
일단 결론만 말하자면
super(ChildB, self).__init__() => python 2.x version code
super().__init__() => python 3.x version code
라고 생각하면 된다.
super()를 사용하면 자동으로 상속 받은 부모 클래스의 초기화 함수를 호출하지만,
ClassA처럼 " Base.__init__(self)"를 통해 직접 호출도 가능하다.
만약에 부모 클래스의 초기화 함수가 인자를 받는 다면 다음과 같이 하면 끝이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Base(object): def __init__(self, a): print("Base created %d" %a) class ChildA(Base): def __init__(self): Base.__init__(self,10) print("childA") class ChildB(Base): def __init__(self): super(ChildB, self).__init__(10) print("childB") class ChildC(Base): def __init__(self): super().__init__(6) print("childC") ChildA() ChildB() ChildC() | cs |
|
| 결과 :
Base created 10
childA
Base created 10
childB
Base created 6
childC |
|
참고 : https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods