在理解中使用python3的super似乎总是得到TypeError: super(type, obj): obj must be an instance or subtype of type
(但使用Python2的super确实如预期的那样有效)
class A(object):
def __repr__(self):
return "hi!"
class B(A):
def __repr__(self):
return "".join(super().__repr__() for i in range(2))
repr(B())
#output: <repr(<__main__.B at 0x7f70cf36fcc0>) failed: TypeError: super(type, obj): obj must be an instance or subtype of type>
class C(A):
def __repr__(self):
s = ''
for i in range(4):
s += super().__repr__()
return s
repr(C())
#output: hi!hi!hi!hi!
class D(A):
def __repr__(self):
return "".join(super(D,self).__repr__() for i in range(4))
repr(D())
#output: hi!hi!hi!hi!
那么,为什么新super()
在发电机理解上失败了呢?
增编:
In [28]: class E(A):
....: def __repr__(self):
....: def inner():
....: print(repr(__class__))
....: inner()
....: return ''
In [29]: repr(E())
<class '__main__.E'>
Out[29]: ''
In [30]: class F(A):
....: def __repr__(self):
....: return "".join([super().__repr__() for i in range(4)])
....:
In [31]: repr(F())
TypeError: super(type, obj): obj must be an instance or subtype of type