【发布时间】:2018-07-22 17:26:28
【问题描述】:
下面的玩具示例看起来有点奇怪,但它尽可能简单地说明了问题。
首先,没有问题的部分:
class TupleWrapper(tuple):
def __new__(cls, ignored):
return super(TupleWrapper, cls).__new__(cls, [1, 2, 3])
TupleWrapper 类接受一个任意的 an,返回一个类似于常量 (1, 2, 3) 的类似元组的对象。例如:
>>> TupleWrapper('foo')
(1, 2, 3)
>>> TupleWrapper(8)
(1, 2, 3)
到目前为止一切顺利。
现在,考虑这个类:
class ListWrapper(list):
def __new__(cls, ignored):
return super(ListWrapper, cls).__new__(cls, [1, 2, 3])
它与TupleWrapper 相同,只是它是list 的子类,而不是tuple。因此,我期望以下
>>> ListWrapper('foo')
[1, 2, 3]
>>> ListWrapper(8)
[1, 2, 3]
其实我得到的是
>>> ListWrapper('foo')
['f', 'o', 'o']
>>> ListWrapper(8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
FWIW,我使用的是 Python 2.7.13。
谁能帮我理解这种行为差异?
是否有可能理解它,或者它只是一个必须忍受的“怪癖之一”?
【问题讨论】:
标签: python subclass subclassing