简体   繁体   English

在Python中实现__concat__

[英]Implementing __concat__ in Python

I tried to implement __concat__ , but it didn't work 我尝试实现__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'

How can I fix this? 我怎样才能解决这个问题?

__concat__ is not a special method ( http://docs.python.org/glossary.html#term-special-method ). __concat__不是一种特殊的方法( 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. 您将需要实现__add__以获得所需的行为。

You want to implement __add__ , not __concat__ . 您要实现__add__而不是__concat__ There's no __concat__ special method in Python. Python中没有__concat__特殊方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM