python super() 函数
描述
super() 函数是用于调用父类(超类)的一个方法。
super() 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(mro)、重复调用(钻石继承)等种种问题。
mro 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
语法以下是 super() 方法的语法:
super(type[, object-or-type])参数
- type -- 类。
- object-or-type -- 类,一般是 self
python3.x 和 python2.x 的一个区别是: python 3 可以使用直接使用 super().xxx 代替 super(class, self).xxx :
python3.x 实例:
class a:
def add(self, x):
y = x+1 print(y) class b(a):
def add(self, x):
super().add(x) b = b() b.add(2) # 3
python2.x 实例:
#!/usr/bin/python # -*- coding: utf-8 -*- class a(object): # python2.x 记得继承 object def add(self, x):
y = x+1 print(y) class b(a):
def add(self, x):
super(b, self).add(x) b = b() b.add(2) # 3
无。
实例
以下展示了使用 super 函数的实例:
实例
#!/usr/bin/python # -*- coding: utf-8 -*- class fooparent(object):
def __init__(self):
self.parent = 'i'm the parent.' print ('parent')
def bar(self,message):
print ("%s from parent" % message) class foochild(fooparent):
def __init__(self):
# super(foochild,self) 首先找到 foochild 的父类(就是类 fooparent),然后把类 foochild 的对象转换为类 fooparent 的对象 super(foochild,self).__init__()
print ('child')
def bar(self,message):
super(foochild, self).bar(message) print ('child bar fuction') print (self.parent) if __name__ == '__main__':
foochild = foochild() foochild.bar('helloworld')
执行结果:
parent child helloworld from parent child bar fuction i'm the parent.
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!