【问题标题】:Why this difference between subclassing tuple and subclassing list?为什么子类化元组和子类化列表之间存在这种差异?
【发布时间】: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


    【解决方案1】:

    不同之处在于元组是不可变的,所以所有工作都在__new__ 中完成。列表是可变的,所以它们的构造发生在__init__。您还没有重写 list.__init__ 方法,所以它仍然像往常一样构造列表。

    PS:从列表或元组等内置函数继承通常是令人沮丧和失望的体验,所以不要打扰:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 2011-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多