【问题标题】:problem subclassing builtin type问题子类化内置类型
【发布时间】:2011-06-17 04:07:33
【问题描述】:
# Python 3
class Point(tuple):
    def __init__(self, x, y):
        super().__init__((x, y))

Point(2, 3)

会导致

TypeError: tuple() 最多取 1 论据(给定 2 个)

为什么?我应该怎么做?

【问题讨论】:

标签: python python-3.x subclassing built-in-types


【解决方案1】:

tuple 是不可变类型。在 __init__ 被调用之前,它已经被创建并且不可变。这就是为什么这不起作用。

如果你真的想继承一个元组,使用__new__。

>>> class MyTuple(tuple):
...     def __new__(typ, itr):
...             seq = [int(x) for x in itr]
...             return tuple.__new__(typ, seq)
... 
>>> t = MyTuple((1, 2, 3))
>>> t
(1, 2, 3)

【讨论】:

  • 啊,所以我的Point(2,3) 在Point 中寻找__new__ 方法,找不到它,调用tuple.__new__(Point,2,3) 失败,因为它不简单地将任意数量的参数传递给__init__ 就像用户定义的类一样,但实际上需要一个迭代器来正确初始化 tuple,对吗?代码甚至没有到达Point.__init__(self, 2, 3) 调用;如果确实发生了该调用,那也是不正确的,因为tuple 没有__init__,所以object.__init__ 只会默默地什么都不做?
猜你喜欢
  • 2021-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2010-10-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多