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
在下面的示例中,显示了(即) 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
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短