python super
Posted Lippman
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python super相关的知识,希望对你有一定的参考价值。
super
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
测试1:
A 中有实例方法 foo,BCDE对实例方法重写都为: foo(self): super(X, self),foo()
那么此时foo的调用递归为: E-D-B-C-A 因为EDBC的foo都有super,所以需要调用父类的该方法
- E foo
- D foo
- B foo
- C foo
A do foo - C foo
- B foo
- D foo
- E foo
测试2
如果重写C中的foo: foo(self): print ‘C do foo’ 其他类的foo照旧,
那么此时的foo调用递归为:E-D-B-C 执行C.foo
- E foo
- D foo
- B foo
- C foo
C do foo… - C foo
- B foo
- D foo
- E foo
注意:B和C虽然是并行的,B.foo有super 但是C.foo没有调用super,在程序遇到没有super的重写foo后,会停止对父类foo方法的调用,然后返回递归源头。
测试3 :
如果重写D中的foo: foo(self): print ‘D do foo’ 其他类的foo照旧,
那么此时的foo调用递归为:E-D 执行D.foo
所以super获取到的方法为多继承搜索链上最近一个自定义foo(没有调用super)。
实验代码
!/usr/bin/env python
encoding: utf-8
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
- E foo
- D foo
D do foo - D foo
- E foo
以上是关于python super的主要内容,如果未能解决你的问题,请参考以下文章