您的位置:首页 > 编程语言 > Python开发

Python的build-in函数super()

2016-09-02 23:30 316 查看
用法:super([type[, object-or-type]])
作用:Return a proxy object that delegates method calls to a parent or sibling class of type.

在一个类中,当要使用已经被重载的继承方法的时候,super()十分有用。除了type本身被跳过之外,搜索的顺序和用于getattr()的搜索顺序是一致的。

type的__mro__属性列出了getarr()和super()使用的method resolution搜索顺序。该属性是动态的,当inheritance hierarchy变换的时候,它也会变换。

如果调用时,忽略第二个参数,返回的super object是未绑定的。如果第二个参数是一个对象,则isinstance(obj,type)一定为真;如果第二个参数是一个类型,则issubclass(type2, type)为真(常常用于classmethods).

super()的两种典型用法:

1.In a class hierarchy with single inheritance, super can
be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in
other programming languages.(继承的父类为一个的时候,用于refer to父类)

2.The second use case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only
support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method have the same calling signature in every case (because the order of calls is determined
at runtime, because that order adapts to changes in the class hierarchy, and because that order can include sibling classes that are unknown prior to runtime).

该种用法是python所特有的,用于支持在dynamic execution environment中的 cooperative multiple inheritance。diamond
diagrams:多个子类实现同一方法。

典型的super()使用方法:

class C(B):
def metrhd(self,arg):
super().method(arg) #等同于super(C,self).method(arg)


Note that 
super()
 is
implemented as part of the binding process for explicit dotted attribute lookups such as
super().__getitem__(name)
.
It does so by implementing its own 
__getattribute__()
 method
for searching classes in a predictable order that supports cooperative multiple inheritance. Accordingly, 
super()
 is
undefined for implicit lookups using statements or operators such as 
super()[name]
.

注意:super()可以用于explicit dotted atrribute的查找和绑定,其原因是自身的
__getattribute__()
方法支持
cooperative
multiple inheritance并以确定的顺序搜索。

Also note that, aside from the zero argument form, 
super()
 is
not limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references. The zero argument form only works inside a class definition, as the compiler fills in the necessary details to correctly retrieve
the class being defined, as well as accessing the current instance for ordinary methods.

注意:super()并不仅限于inside methods中使用。零参数的super()只能用于class的定义中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 对象