super() 函数是用于调用父类(超类)的一个方法。 语法 super(type[, object-or-type]) 参数 super(SubClass, self).method() 的意思是,根据self去找SubClass的'父亲’,然后调用这个'父亲’的method() 。 super(本类名,self) Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx : Python 3.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 Python 2.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. 如果在子类中也定义了_init_()函数,那么该如何调用基类的_init_()函数: class C(P): def __init__(self): P.__init__(self) print 'calling Cs construtor' 方法二、使用super()方法 : Python中的super()方法设计目的是用来解决多重继承时父类的查找问题,所以在单重继承中用不用 super 都没关系;但是,使用 super() 是一个好的习惯。一般我们在子类中需要调用父类的方法时才会这么用。 MRO(Method Resolution Order):python对于每一个类都有一个MRO列表。此表的生成有以下原则:子类永远在父类之前,如果有多个父类,那么按照它们在列表中的顺序被检查,如果下一个类有两个合法的选择,那么就只选择第一个。 class A(object): def __init__(self): self.n = 10 def minus(self, m): self.n -= mclass B(A): def __init__(self): self.n = 7 def minus(self, m): super(B, self).minus(m) self.n -= 2b = B() b.minus(2)print(b.n)class C(A): def __init__(self): self.n = 12 def minus(self, m): super(C, self).minus(m) self.n -= 5class D(B, C): def __init__(self): self.n = 15 def minus(self, m): super(D, self).minus(m) self.n -= 2d = D() d.minus(2)print(d.n)print(D.__mro__) 结果: 3 4(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>) |
|