[python] super() 정리!

About_work·2024년 2월 23일
0

python 기초

목록 보기
38/56

1. 인자 없이 super() 사용하기

  • 파이썬 3에서는 super()를 인자 없이 호출할 수 있습니다. 이 경우, 파이썬은 현재 메소드를 호출하는 클래스와 해당 인스턴스(self)를 자동으로 인지하여, 현재 클래스의 가장 가까운 부모를 찾습니다.
class Parent:
    def method(self):
        return 'Parent method'

class Child(Parent):
    def method(self):
        result = super().method()  # 인자 없이 super() 호출
        return f'Child extends {result}'
  • 여기서 super().method()는 현재 클래스(Child)의 부모 클래스인 Parentmethod를 호출합니다.

2. 인자를 포함하여 super() 사용하기

super(class, instance)
  • class:
    • 기준 클래스를 나타냅니다.
    • 이 클래스의 MRO(Method Resolution Order)에 따라, 기준 클래스 다음에 위치하는 부모 클래스가 return됨
  • instance:
    • class의 인스턴스를 나타냅니다.
    • super()는 이 인스턴스를 기반으로 메소드를 호출
class A:
    def method(self):
        return 'A method'

class B(A):
    def method(self):
        return 'B method'

class C(A):
    def method(self):
        return 'C method'

class D(B, C):
    def method(self):
        return super(B, self).method()  # B를 넘기면 C의 method를 호출
>>> 'C method'
  • D 클래스의 인스턴스에서 method()를 호출하면, super(B, self).method()B의 MRO를 따라 Cmethod를 호출
  • 여기서 B가 첫 번째 인자로 사용되므로, B의 부모 클래스 중 B 다음에 오는 클래스의 메소드가 호출

반환 값

profile
새로운 것이 들어오면 이미 있는 것과 충돌을 시도하라.

0개의 댓글