首页 > 编程语言 > 详细

python super()函数

时间:2019-06-08 20:23:41      阅读:116      评论:0      收藏:0      [点我收藏+]

描述:

super()函数用于调用父类(超类)的一个方法。

super()函数是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没有问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

MRO就是类等方法解析顺序表,其实也就是继承父类方法时的顺序表。

语法:

以下是super()方法的语法:

super(type[object-or-type])

 参数:

  • type --类
  • object-or-type --类,一般是self

实例:

 1 class FooParent(object):
 2     def __init__(self):
 3         self.parent = I\‘m the parent.
 4         print(Parent)
 5 
 6     def bar(self,message):
 7         print("%s from Parent" % message)
 8 
 9 class FooChild(FooParent):
10     def __init__(self):
11         # super() 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
12         super().__init__()
13         print(Child)
14 
15     def bar(self,message):
16         super().bar(message)
17         print(Child bar function)
18         print(self.parent)
19 
20 if __name__ == __main__:
21     fooChild = FooChild()
22     fooChild.bar(helloworld)

 

python super()函数

原文:https://www.cnblogs.com/helloTerry1987/p/10991481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!