Computer >> Máy Tính >  >> Lập trình >> Python

Super () của Python hoạt động như thế nào với đa kế thừa?

Trước khi giải thích về super () trước tiên chúng ta cần biết về đa kế thừa khái niệm.

Nhiều kế thừa :Có nghĩa là một lớp con có thể kế thừa nhiều lớp cha.

Trong ví dụ sau Lớp con kế thừa các phương thức thuộc tính từ lớp Cha.

Ví dụ

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()

Đầu ra

Father : Srinivas
Mother : Anjali


Trong ví dụ sau cho thấy (tức là) super ( ) hoạt động với nhiều kế thừa

siêu () :Hàm super có thể được sử dụng để thay thế lệnh gọi rõ ràng tới

Ví dụ

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()

Khi bạn chạy chương trình, đầu ra sẽ là

Đầu ra

i am here
Father : Srinivas
Mother : Anjali