python super()使用详解

1.super的作用
调用父类方法
2.单继承使用示例

#coding:utf-8
#单继承
class A(object):
    def __init__(self):
        self.n=2
    def add(self,m):
        self.n+=m
class B(A):
    def __init__(self):
        self.n=3
    def add(self,m):
        super(B,self).add(m)
        self.n+=3
b=B()
b.add(3)
print b.n

运行结果:

super(B,self)参数说明:
1)B:调用的是B的父类的方法。
2)self:子类的实例
3.多继承使用示例

#多继承
class A(object):
    def __init__(self):
        self.n=2
    def add(self,m):
        print "A"
        self.n+=m
class B(A):
    def __init__(self):
        self.n=3
    def add(self,m):
        print "B"
        super(B,self).add(m)
        self.n+=3
class C(A):
    def __init__(self):
        self.n=4
    def add(self,m):
        print "C"
        super(C,self).add(m)
        self.n+=4
class D(B,C):
    def __init__(self):
        self.n=5
    def add(self,m):
        print "D"
        super(D,self).add(m)
        self.n+=5
print D.__mro__
d=D()
d.add(3)
print d.n

运行结果:

python中__mro__属性,表示类的线性解析顺序, 新式类使用广度优先搜索,来确定父类调用顺序。
如上例中,D类__mro__的值为[D,B,C,A,object],因此,super(D,self).add(m)会先调用B的add方法,
super(B,self).add(m)会先调用C的add方法,super(C,self).add(m)会先调用A的add方法,结果为20

原文地址:https://www.cnblogs.com/shijingjing07/p/7081944.html