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
以下示例展示 ( i.e) super() 如何与多重继承一起使用
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):
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP