在Python中实现__concat__

2 投票
2 回答
535 浏览
提问于 2025-04-15 20:09

我尝试实现 __concat__ 这个功能,但没有成功。

>>> class lHolder():
...     def __init__(self,l):
...             self.l=l
...     def __concat__(self, l2):
...             return self.l+l2
...     def __iter__(self):
...             return self.l.__iter__()
... 
>>> lHolder([1])+[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'lHolder' and 'list'

我该怎么解决这个问题呢?

2 个回答

2

你想要实现的是 __add__,而不是 __concat__。在Python里没有 __concat__ 这个特殊的方法。

5

__concat__ 不是一个特殊的方法(你可以在这里了解什么是特殊方法:http://docs.python.org/glossary.html#term-special-method)。它属于操作符模块。

你需要实现 __add__ 方法,才能得到你想要的效果。

撰写回答