Python的build-in函数super()


用法: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 inheritancediamond 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 assuper().__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的定义中。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值