python-3.x - python - super()可打印表示形式

sup = super(B, self)sup2 = super(B, B)具有难以区分的表示形式,它们都看起来像这样:


<super: <class 'B'>, <B object>>



虽然super(B, self).spam提供了绑定方法,但super(B, B)只适用于类方法,因此super(B, B).cls_spam(),如下所示,不能将它用于常规方法,得到一个正常函数:


class A:


 @classmethod


 def cls_spam(cls):


 print('A.cls_spam: cls =', cls)



 def spam(self):


 print('A.spam: self =', self)



class B(A):


 def call_spam(self):


 sup = super(B, self)


 print('B.call_spam: sup =', sup)


 print('B.call_spam: sup.spam =', sup.spam)


 print('B.call_spam: sup.cls_spam =', sup.cls_spam)


 sup.spam()


 sup.cls_spam()



 sup2 = super(B, B)


 print('B.call_spam: sup2 =', sup2)


 print('B.call_spam: sup2.css_spam =', sup2.cls_spam)


 # can't call sup2.spam(), not without giving it self explicitly


 sup2.cls_spam()



以下交互式会话说明了:


>>> b = B()


>>> b.call_spam3()


B.call_spam: sup = <super: <class 'B'>, <B object>>


B.call_spam: sup.spam = <bound method A.spam of <__main__.B object at 0x108830b50>>


B.call_spam: sup.cls_spam = <bound method A.cls_spam of <class '__main__.B'>>


A.spam: self = <__main__.B object at 0x108830b50>


A.cls_spam: cls = <class '__main__.B'>


B.call_spam: sup2 = <super: <class 'B'>, <B object>>


B.call_spam: sup2.css_spam = <bound method A.cls_spam of <class '__main__.B'>>


A.cls_spam: cls = <class '__main__.B'>



super()是一门复杂的主题,如果记录的上述行为被记录为文档的理解,那对我会有很大帮助。

使用Python 3.5.3,Debian GNU/Linux 9.11(stretch )

时间:

super()在类方法和常规方法中都很有用,在classmethod中没有实例,只能访问类,因此super()的第二个参数接受实例或类,至少在super()的文档

如果第二个参数是对象,就isinstance(obj, type)必须为true,如果第二个参数是类型,则issubclass(type2,type)必须为true(这对于classmethods很有用)。

如果要区分两个super()实例,可以改为查看__self__属性,该属性表示第三条信息:


>>> sup = super(B, b)


>>> sup.__self__


<__main__.B object at 0x108b4c520>


>>> sup2 = super(B, B)


>>> sup2.__self__


<class '__main__.B'>



repr()输出中可以看到的另外两个信息分别是__thisclass____self_class__属性:


>>> sup.__thisclass__, sup.__self_class__


(<class '__main__.B'>, <class '__main__.B'>)



当你使用不同的类作为第一个参数时,这更容易发现:


>>> sup_a = super(A, b)


>>> sup_a


<super: <class 'A'>, <B object>>


>>> sup_a.__thisclass__, sup_a.__self_class__


(<class '__main__.A'>, <class '__main__.B'>)



...