问题子类化内置类型 [英] problem subclassing builtin type
本文介绍了问题子类化内置类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
# Python 3
class Point(tuple):
def __init__(self, x, y):
super().__init__((x, y))
Point(2, 3)
会导致
TypeError:tuple()最多需要1个 论点(给出2个)
TypeError: tuple() takes at most 1 argument (2 given)
为什么?我该怎么办?
推荐答案
tuple
是不可变的类型.它甚至在调用__init__
之前就已经创建并且不可变.这就是为什么这行不通的原因.
tuple
is an immutable type. It's already created and immutable before __init__
is even called. That is why this doesn't work.
如果您真的想对元组进行子类化,请使用 __new__
.
If you really want to subclass a tuple, use __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)
这篇关于问题子类化内置类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文