Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 super()는 다중 상속에서 어떻게 작동합니까?

<시간/>

super() 를 설명하기 전에 먼저 다중 상속에 대해 알아야 합니다. 개념.

다중 상속 :하나의 하위 클래스가 여러 상위 클래스를 상속할 수 있음을 의미합니다.

다음 예제에서 자식 클래스는 부모 클래스에서 속성 메서드를 상속받았습니다.

class Father:
   fathername = ""
   def father(self):
   print(self.fathername)

class Mother:
   mothername = ""
   def mother(self):
   print(self.mothername)

class Child(Father, Mother):
   def parent(self):
   print("Father :", self.fathername)
   print("Mother :", self.mothername)

s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()

출력

Father : Srinivas
Mother : Anjali


다음 예에서는 ( 즉) 수퍼( ) 다중 상속과 함께 작동

수퍼() :수퍼 함수는

에 대한 명시적 호출을 대체하는 데 사용할 수 있습니다.

class Father:
   fathername = ""
   def father(self):
   print(self.fathername)

class Mother:
   mothername = ""
   def mother(self):
   print(self.mothername)

class Child(Father, Mother):
   def parent(self):
   super().__init__()
   print("i am here")
   print("Father :", self.fathername)
   print("Mother :", self.mothername)

s1 = Child()
s1.fathername = "Srinivas"
s1.mothername = "Anjali"
s1.parent()

프로그램을 실행하면 다음과 같이 출력됩니다.

출력

i am here
Father : Srinivas
Mother : Anjali