使用Python 3中调用super()的4种方法中的哪一种?

使用Python 3中调用super()的4种方法中的哪一种?,第1张

使用Python 3中调用super()的4种方法中的哪一种?

让我们使用以下类进行演示:

class A(object):    def m(self):        print('m')class B(A): pass

绑定

super
对象不会将属性访问分配给类,您必须使用描述符协议:

>>> super(B).mTraceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'super' object has no attribute 'm'>>> super(B).__get__(B(), B)<super: <class 'B'>, <B object>>

super
绑定到实例的对象提供了绑定方法:

>>> super(B, B()).m<bound method B.m of <__main__.B object at 0xb765dacc>>>>> super(B, B()).m()m

super
绑定到类的对象给出函数(根据Python 2的未绑定方法):

>>> super(B, B).m<function m at 0xb761482c>>>> super(B, B).m()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: m() takes exactly 1 positional argument (0 given)>>> super(B, B).m(B())m

见米歇尔Simionato的“事情了解Python的超级”博客文章系列(1,2,3)了解更多信息



欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5645419.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存