标签:
super(type[, object-or-type]) # object-or-type must be instance of type
Return the superclass of type. If the second argument is omitted the super object
returned is unbound. If the second argument is an object, isinstance(obj, type)
must be true. If the second argument is a type, issubclass(type2, type) must be
true. super() only works for new-style classes.
A typical use for calling a cooperative superclass method is: (super常在子类调用超类的方法用到)
class C(B):
def meth(self, arg):
super(C, self).meth(arg)
super 解决在多继承中调用父类方法的问题。
例如:有如下多继承
A
/ \
B C
\ / \
D \
\ |
E
A 中有实例方法 foo,BCDE对实例方法重写都为: foo(self): super(X, self),foo()
那么此时foo的调用递归为: E-D-B-C-A 因为EDBC的foo都有super,所以需要调用父类的该方法
如果重写C中的foo: foo(self): print ‘C do foo’ 其他类的foo照旧,
那么此时的foo调用递归为:E-D-B-C 执行C.foo
如果重写D中的foo: foo(self): print ‘D do foo’ 其他类的foo照旧,
那么此时的foo调用递归为:E-D 执行D.foo
所以super获取到的方法为多继承搜索链上最近一个自定义foo(没有调用super)。
class A(object):
#def new(cls, args, *kwargs):
# print ‘@ A new’
def __init__(self):
print ‘+ A init‘
super(A, self).__init__()
print ‘- A init‘
def foo(self):
print ‘A do foo‘
class B(A):
#def new(cls, args, *kwargs):
# print ‘@ B new’
def __init__(self):
print ‘@ B init‘
def foo(self):
print ‘+ B foo‘
print ‘B do foo‘
#super(B, self).foo()
print ‘- B foo‘
class C(A):
#def new(cls, args, *kwargs):
# print ‘@ C new’
def __init__(self):
print ‘@ C init‘
def foo(self):
print ‘+ C foo‘
#print ‘C do foo...‘
super(C, self).foo()
print ‘- C foo‘
class D(B,C):
#def new(cls, args, kwargs):
# print ‘@ D new’
#return super(D, cls).__new__(cls, args, kwargs)
def __init__(self):
print ‘@ D init‘
def foo(self):
print ‘+ D foo‘
print ‘D do foo‘
#super(D, self).foo()
print ‘- D foo‘
class E(D,C):
def init(self):
print ‘@ E init’
def foo(self):
print ‘+ E foo‘
super(E, self).foo()
print ‘- E foo‘
e = E()
e.foo()
结果:
D:\Python27\python.exe F:/coding/python/1.py
@ E init
标签:
原文地址:http://www.cnblogs.com/ordeder/p/5636900.html