如何在 Python 中初始化元组子类的实例



可能的重复项:
使用多个__init__参数子类化 Python 元组

我想定义一个继承自tuple的类,并且我希望能够使用tuple不支持的语法来实例化它。举一个简单的例子,假设我想定义一个继承自tuple的类MyTuple,并且我可以通过传递两个值 xy 来实例化它来创建(我的)元组(x, y)。我尝试了以下代码:

class MyTuple(tuple):
    def __init__(self, x, y):
        print("debug message")
        super().__init__((x, y))

但是当我尝试时,例如,MyTuple(2, 3)我得到了一个错误:TypeError: tuple() takes at most 1 argument (2 given).似乎我的__init__函数甚至没有被调用(基于我得到的错误以及我的"调试消息"没有打印的事实)。

那么正确的方法是什么呢?

我正在使用Python 3.2。

class MyTuple(tuple):
    def __new__(cls, x, y):
        return tuple.__new__(cls, (x, y))
x = MyTuple(2,3)
print(x)
# (2, 3)

使用 super 的困难之一是您无法控制接下来将调用哪些同名类的方法。因此,所有类的方法都必须共享相同的调用签名 - 至少相同数量的项。由于您正在更改发送给__new__的参数数量,因此不能使用super


或者正如Lattyware所建议的那样,你可以定义一个命名元组,

import collections
MyTuple = collections.namedtuple('MyTuple', 'x y')
p = MyTuple(2,3)
print(p)
# MyTuple(x=2, y=3)
print(p.x)
# 2

另一种方法是封装元组而不是从中继承:

>>> class MyTuple(object):
    count = lambda self, *args: self._tuple.count(*args)
    index = lambda self, *args: self._tuple.index(*args)
    __repr__ = lambda self: self._tuple.__repr__()
    # wrap other methods you need, or define them yourself,
    # or simply forward all unknown method lookups to _tuple
    def __init__(self, x, y):
        self._tuple = x,y

>>> x = MyTuple(2,3)
>>> x
(2, 3)
>>> x.index(3)
1

这有多实用,取决于你需要多少功能和修改,以及你需要isinstance(MyTuple(2, 3), tuple)

最新更新