【发布时间】:2023-03-11 02:58:02
【问题描述】:
class TrafficData(object):
def __init__(self):
self.__data = {}
def __getitem__(self, epoch):
if not isinstance(epoch, int):
raise TypeError()
return self.__data.setdefault(epoch, ProcessTraffic())
def __iadd__(self, other):
for epoch, traffic in other.iteritems():
# these work
#existing = self[epoch]
#existing += traffic
# this does not
self[epoch] += traffic # here the exception is thrown
return self
在上面的精简代码中,我不希望有一个项目分配,但显然在标记的行上发生了一个,并抛出以下异常:
File "nethogs2.py", line 130, in __iadd__
self[epoch] += traffic
TypeError: 'TrafficData' object does not support item assignment
但是,如果我改用前面的 2 行注释掉的行,则不会引发异常。
在我看来,2 应该以相同的方式运行。 self[epoch] 返回对对象的引用,并通过对象__iadd__ 对其进行了适当的修改。我在这里有什么误解?我在使用字典时经常遇到这个问题。
更新0
可能值得指出的是self.__data 中的值定义了__iadd__,但没有定义__add__,如果可能的话,我更愿意修改该值。我还想避免创建__setitem__ 方法。
更新1
下面是一个演示问题的测试用例,我将上面的代码留作现有答案。
class Value(object):
def __init__(self, initial=0):
self.a = initial
def __iadd__(self, other):
self.a += other
return self
def __str__(self):
return str(self.a)
class Blah(object):
def __init__(self):
self.__data = {}
def __getitem__(self, key):
return self.__data.setdefault(key, Value())
a = Blah()
b = a[1]
b += 1
print a[1]
a[1] += 2
print a[1]
【问题讨论】:
标签: python variable-assignment dictionary