码迷,mamicode.com
首页 > 编程语言 > 详细

python super

时间:2016-07-03 10:30:06      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/ordeder/p/5636900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!