【发布时间】:2018-10-01 03:28:07
【问题描述】:
我只想使用 __add__ 修饰符,使用 '+=' 轻松添加到类实例的元素:
class Problem:
def __init__(self):
self.lItems = []
def __add__(self, other):
self.lItems.append(other)
problem = Problem()
problem += 'text'
print(problem)
在+= 之后,产生的问题将等于None。为什么?我怎样才能防止这种情况发生?
P.S.:我也尝试过实现__iadd__,但没有任何效果......
【问题讨论】:
-
__add__需要返回一个值。 -
即使
def __add__(self, other): return self.lItems.append(other)也不起作用... -
否,因为
append本身返回无。
标签: python python-3.x class operator-overloading