Skip to main content
 首页 » 编程设计

python之在 Python 中实现 __concat__

2025年05月04日14www_RR

我尝试实现__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' 

我该如何解决这个问题?

请您参考如下方法:

__concat__ 不是特殊方法 ( http://docs.python.org/glossary.html#term-special-method )。它是运算符(operator)模块的一部分。

您将需要实现 __add__ 以获得您想要的行为。