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

'Python > python' 카테고리의 다른 글

ipynb file import 방법  (0) 2018.07.19

jupyter notebook 쓰다가 알게된 팁이있다

 

자체적으로 내가 작성한 ipynb file을 import 하고 싶을 때가 있는데

 

일일히 파이썬파일로 변경 후 load했는데 더 간단한 방법이 있었다.

 

 

1. import_ipynb 모듈설치

 

2. import import_ipynb

 

import import_ipynb
import LoadCIFARData
 
>>> importing Jupyter notebook from LoadCIFARData.ipynb
 

 

위 코드의 결과는 내가 작성한 LoadCIFARData.ipynb 를 load한다! 끝

'Python > python' 카테고리의 다른 글

python super function  (0) 2018.07.20

+ Recent posts