Python

super()

쉽게가자 2020. 5. 22. 20:35

미리 정의된 클래스를 상속받아 새로운 클래스를 만들때, 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

 

Built-in Functions — Python 3.8.3 documentation

Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer or a floating po

docs.python.org


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) 메소드를 호출할 때 유용함.