-
미리 정의된 클래스를 상속받아 새로운 클래스를 만들때, super()를 자주 보게된다.
class Parent(object) { def __init(self)__: print('I am parent') } class Child(Parent) { def __init(self)__: super(Parent, self) print('I am child') }
보통 이런식으로 사용되는것 같은데, 왜 심플한 파이썬에서 이렇게 명시적으로 부모의 생성자를 불러줘야 하는걸까?
정확히 super()는 어떤 경우에 사용하는 걸까? 파이썬 공식 문서를 조금 살펴보기로 했다.
*참조: https://docs.python.org/3/library/functions.html#super
super([type[, object-or-type]])¶
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
이렇게 적혀있는다. 한국어로 정리해 보면, 이정도가 되겠다.
- 프록시 오브젝트를 반환하는 함수
- 프록시 오브젝트는 메소드를 호출 시, 이를 부모나 형제 클래스로 위임(delegate) 한다고 함.
- 즉, 부모나 형제 클래스의 메소드를 호출하기 위한 오브젝트를 반환해준다는 뜻.
- 상속을 하면서 재정의된(overriden) 메소드를 호출할 때 유용함.
'Python' 카테고리의 다른 글
File Objects (0) 2020.08.22 argparse 모듈로 커맨드라인 인자 가져오기 (0) 2020.05.28 (A,) <-- 콤마는 왜쓰는걸까? (1D Tuple) (0) 2020.05.23