Python의 super() 함수는 부모 클래스를 명시적으로 참조할 수 있게 해줍니다. 이는 상속의 경우에 유용하며, 슈퍼 클래스 함수를 호출하고자 할 때 사용됩니다.
Python super
Python super 함수에 대해 이해하기 위해서는 Python 상속에 대해 알아야 합니다. Python 상속에서는 하위 클래스가 상위 클래스를 상속받습니다. Python super() 함수를 사용하면 상위 클래스를 암묵적으로 참조할 수 있습니다. 따라서 Python super는 우리의 작업을 더 쉽고 편안하게 만들어줍니다. 하위 클래스에서 상위 클래스를 참조할 때, 상위 클래스의 이름을 명시적으로 작성할 필요가 없습니다. 다음 섹션에서는 Python super 함수에 대해 논의하겠습니다.
Python super 함수 예제
먼저, 우리의 Python 상속 튜토리얼에서 사용한 다음 코드를 살펴보세요. 예제 코드에서 상위 클래스는 Person
이고 하위 클래스는 Student
입니다. 코드는 아래와 같이 표시됩니다.
class Person:
# 변수 초기화
name = ""
age = 0
# 생성자 정의
def __init__(self, person_name, person_age):
self.name = person_name
self.age = person_age
# 클래스 메서드 정의
def show_name(self):
print(self.name)
def show_age(self):
print(self.age)
# 서브클래스 정의 시작
class Student(Person):
studentId = ""
def __init__(self, student_name, student_age, student_id):
Person.__init__(self, student_name, student_age)
self.studentId = student_id
def get_id(self):
return self.studentId # returns the value of student id
# 서브클래스 정의 종료
# 슈퍼클래스의 객체 생성
person1 = Person("Richard", 23)
# 객체의 멤버 메서드 호출
person1.show_age()
# 서브클래스의 객체 생성
student1 = Student("Max", 22, "102")
print(student1.get_id())
student1.show_name()
위의 예시에서, 우리는 부모 클래스 함수를 호출했습니다:
Person.__init__(self, student_name, student_age)
이를 아래와 같이 파이썬의 super 함수 호출로 대체할 수 있습니다:
super().__init__(student_name, student_age)
두 경우 모두 출력은 동일하게 유지되며, 아래 이미지에 표시되어 있습니다.
Python 3 super
위 문법은 파이썬 3의 super 함수를 위한 것입니다. 파이썬 2.x 버전을 사용하고 있다면 약간 다르며, 다음과 같은 변경을 해야합니다:
class Person(object):
...
super(Student, self).__init__(student_name, student_age)
첫 번째 변경은 Person에 object
를 기본 클래스로 사용하는 것입니다. Python 2.x 버전에서 super 함수를 사용하기 위해서는 이렇게 해야합니다. 그렇지 않으면 다음과 같은 오류가 발생합니다.
Traceback (most recent call last):
File "super_example.py", line 40, in <module>
student1 = Student("Max", 22, "102")
File "super_example.py", line 25, in __init__
super(Student, self).__init__(student_name, student_age)
TypeError: must be type, not classobj
두 번째 변경은 super 함수 자체의 구문입니다. 파이썬 3의 super 함수를 사용하는 것보다 훨씬 쉽고 구문도 깔끔합니다.
다중 상속을 가진 Python super 함수
이전에 말했듯이 Python super() 함수를 사용하면 우리는 슈퍼클래스를 암묵적으로 참조할 수 있습니다. 그러나 다중 상속의 경우 어떤 클래스를 참조할까요? 음, Python super()는 항상 가장 가까운 슈퍼클래스를 참조합니다. 또한 Python super() 함수는 __init__()
함수뿐만 아니라 슈퍼클래스의 다른 모든 함수를 호출할 수도 있습니다. 따라서 다음 예제에서 확인해 보겠습니다.
class A:
def __init__(self):
print('Initializing: class A')
def sub_method(self, b):
print('Printing from class A:', b)
class B(A):
def __init__(self):
print('Initializing: class B')
super().__init__()
def sub_method(self, b):
print('Printing from class B:', b)
super().sub_method(b + 1)
class C(B):
def __init__(self):
print('Initializing: class C')
super().__init__()
def sub_method(self, b):
print('Printing from class C:', b)
super().sub_method(b + 1)
if __name__ == '__main__':
c = C()
c.sub_method(1)
위의 Python 3 다중 상속 예제의 출력을 확인해 봅시다.
Initializing: class C
Initializing: class B
Initializing: class A
Printing from class C: 1
Printing from class B: 2
Printing from class A: 3
출력 결과에서 우리는 명확히 볼 수 있듯이 클래스 C의 __init__()
함수가 먼저 호출되고, 그 다음에 클래스 B의 함수가 호출되고, 그 후에 클래스 A의 함수가 호출됩니다. sub_method()
함수를 호출할 때도 비슷한 일이 발생했습니다.
Python super 함수가 필요한 이유
만약 Java 언어에 이전 경험이 있다면, 그곳에서 기본 클래스는 super 객체에 의해 호출된다는 것을 알고 있을 것입니다. 따라서 이 개념은 실제로 개발자들에게 유용합니다. 그러나 Python도 프로그래머가 슈퍼클래스 이름을 사용하여 참조할 수 있는 기능을 제공합니다. 그리고, 프로그램에 다중 상속이 포함되어 있다면, 이 super() 함수는 도움이 됩니다. 이것이 파이썬 super 함수에 대한 전부입니다. 이 주제를 이해하셨기를 바랍니다. 질문이 있으시면 댓글란을 이용해 주세요.
더 많은 파이썬 스크립트와 예제는 저희 GitHub 저장소에서 확인하실 수 있습니다.
참고: 공식 문서
Source:
https://www.digitalocean.com/community/tutorials/python-super