max*_*max 6 python built-in-types subclassing python-3.x
# Python 3
class Point(tuple):
def __init__(self, x, y):
super().__init__((x, y))
Point(2, 3)
Run Code Online (Sandbox Code Playgroud)
会导致
TypeError:tuple()最多需要1个参数(给定2个)
为什么?我该怎么做呢?
use*_*312 10
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1221 次 |
| 最近记录: |