Implementing __concat__ in Python

蓝咒 提交于 2019-12-11 07:05:26

问题


I tried to implement __concat__, but it didn't work

>>> 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'

How can I fix this?


回答1:


__concat__ is not a special method (http://docs.python.org/glossary.html#term-special-method). It is part of the operator module.

You will need to implement __add__ to get the behaviour you want.




回答2:


You want to implement __add__, not __concat__. There's no __concat__ special method in Python.



来源:https://stackoverflow.com/questions/2400561/implementing-concat-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!