웹사이트 검색

파이썬 슈퍼() - 파이썬 3 슈퍼()


Python super() 함수를 사용하면 부모 클래스를 명시적으로 참조할 수 있습니다. 상위 클래스 함수를 호출하려는 상속의 경우에 유용합니다.

파이썬 슈퍼

파이썬 슈퍼 함수를 이해하려면 파이썬 상속에 대해 알아야 합니다. Python 상속에서 하위 클래스는 상위 클래스에서 상속됩니다. Python super() 함수를 사용하면 암시적으로 수퍼클래스를 참조할 수 있습니다. 따라서 Python super는 작업을 더 쉽고 편안하게 만듭니다. 하위 클래스에서 상위 클래스를 참조할 때 상위 클래스의 이름을 명시적으로 작성할 필요는 없습니다. 다음 섹션에서는 파이썬 슈퍼 함수에 대해 논의할 것입니다.

파이썬 슈퍼 함수 예제

처음에는 Python Inheritance 자습서에서 사용한 다음 코드를 살펴보십시오. 이 예제 코드에서 슈퍼클래스는 Person이고 서브클래스는 Student입니다. 그래서 코드는 아래와 같습니다.

class Person:
    # initializing the variables
    name = ""
    age = 0

    # defining constructor
    def __init__(self, person_name, person_age):
        self.name = person_name
        self.age = person_age

        # defining class methods

    def show_name(self):
        print(self.name)

    def show_age(self):
        print(self.age)


# definition of subclass starts here
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


# end of subclass definition


# Create an object of the superclass
person1 = Person("Richard", 23)
# call member methods of the objects
person1.show_age()
# Create an object of the subclass
student1 = Student("Max", 22, "102")
print(student1.get_id())
student1.show_name()

위의 예에서 부모 클래스 함수를 다음과 같이 호출했습니다.

Person.__init__(self, student_name, student_age) 

아래와 같이 이것을 파이썬 슈퍼 함수 호출로 대체할 수 있습니다.

super().__init__(student_name, student_age)

파이썬 3 슈퍼

위의 구문은 Python 3 수퍼 함수용입니다. Python 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

슈퍼 함수 자체 구문의 두 번째 변경 사항입니다. 보시다시피 파이썬 3 슈퍼 함수는 사용하기 훨씬 쉽고 구문도 깨끗해 보입니다.

다단계 상속을 사용하는 Python 슈퍼 함수

이전에 언급했듯이 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( ) 함수.

파이썬 슈퍼 함수가 필요한 이유

Java 언어에 대한 이전 경험이 있는 경우 기본 클래스도 거기에 있는 수퍼 객체에 의해 호출된다는 것을 알아야 합니다. 따라서 이 개념은 코더에게 실제로 유용합니다. 그러나 Python은 프로그래머가 상위 클래스 이름을 사용하여 참조할 수 있는 기능도 유지합니다. 그리고 프로그램에 다단계 상속이 포함되어 있으면 이 super() 함수가 도움이 됩니다. 이것이 파이썬 슈퍼 함수에 관한 전부입니다. 이 주제를 이해하셨기를 바랍니다. 문의사항은 댓글란을 이용해주세요.

GitHub 리포지토리에서 전체 Python 스크립트와 더 많은 Python 예제를 확인할 수 있습니다.

참조: 공식 문서