Python `+;=`导致类实例为'none'
我只想使用Python `+;=`导致类实例为'none',python,python-3.x,class,operator-overloading,Python,Python 3.x,Class,Operator Overloading,我只想使用\uuuu add\uuuu修饰符,使用“+=”轻松添加到classinstance的元素: class Problem: def __init__(self): self.lItems = [] def __add__(self, other): self.lItems.append(other) problem = Problem() problem += 'text' print(problem) 在+=之后,产生的问题将等
\uuuu add\uuuu
修饰符,使用“+=”轻松添加到classinstance的元素:
class Problem:
def __init__(self):
self.lItems = []
def __add__(self, other):
self.lItems.append(other)
problem = Problem()
problem += 'text'
print(problem)
在+=
之后,产生的问题将等于None
。为什么?我怎样才能防止这种情况发生
附言:我也尝试过实施
\uuuuu iadd\uuuuuuuu
,但没有效果…制作\uuuuuu add\uuuuuu
返回self
的诀窍是:
class Problem:
def __init__(self):
self.lItems = []
def __add__(self, other):
self.lItems.append(other)
return self
problem = Problem()
problem += 'text'
print(problem)
print(problem.lItems)
产出:
<__main__.Problem object at 0x04BBDCD0>
['text']
[“文本”]
编辑:
你应该考虑使用代替。< /p> < p>制作<代码>
class Problem:
def __init__(self):
self.lItems = []
def __add__(self, other):
self.lItems.append(other)
return self
problem = Problem()
problem += 'text'
print(problem)
print(problem.lItems)
产出:
<__main__.Problem object at 0x04BBDCD0>
['text']
[“文本”]
编辑:
你应该考虑使用它代替.在你的代码>追加< /COD>操作之后,你需要<代码>返回对象。< /P>
class Problem:
def __init__(self):
self.lItems = []
def __iadd__(self, other):
self.lItems.append(other)
return self
范例
>>> problem = Problem()
>>> problem += 'text'
>>> problem.lItems
['text']
>>> problem += 'foobar'
>>> problem.lItems
['text', 'foobar']
执行
append
操作后,需要返回对象
class Problem:
def __init__(self):
self.lItems = []
def __iadd__(self, other):
self.lItems.append(other)
return self
范例
>>> problem = Problem()
>>> problem += 'text'
>>> problem.lItems
['text']
>>> problem += 'foobar'
>>> problem.lItems
['text', 'foobar']
您需要从\uuuu add\uuuu
返回实例的新状态:
class Problem:
def __init__(self):
self.lItems = []
def __add__(self, other):
self.lItems.append(other)
return self
但是,现在单独使用+时会出现问题:
a = Problem()
b = a + 5
print (a)
print (b)
结果:
<__main__.Problem instance at 0x0022BE40>
<__main__.Problem instance at 0x0022BE40>
。。。并且使用+会导致错误,这是应该的。您需要从\uuuuu add\uuuuu
返回实例的新状态:
class Problem:
def __init__(self):
self.lItems = []
def __add__(self, other):
self.lItems.append(other)
return self
但是,现在单独使用+时会出现问题:
a = Problem()
b = a + 5
print (a)
print (b)
结果:
<__main__.Problem instance at 0x0022BE40>
<__main__.Problem instance at 0x0022BE40>
。。。使用+会导致错误,这是应该的。需要返回一个值。即使是def\uuu添加(self,other):返回self.lItems.append(other)
不起作用,因为append
本身不返回任何值。def\uu add\uuuuu
需要返回一个值。甚至def\uu add(self,other):return self.lItems.append(other)
不起作用…否,因为append
本身不返回任何值。