谁能告诉我为什么这段代码抱怨没有__setitem__
容器吗?我以为我只需要__getitem__
在容器上获取项目然后__iadd__
设置值,不知道为什么会这样__setitem__
class Item:
def __init__(self):
pass
def __iadd__(self, value):
print 'added: ' + value
return self
class Container:
def __init__(self):
self.__items = {
'foo': Item()
}
def __getitem__(self, name):
return self.__items[name]
if __name__ == '__main__':
# works!
con = Container()
item = con['foo']
item += 'works!'
# wtf?
con['foo'] += "what's going on?"
# output:
# added: works!
# added: what's going on?
# Traceback (most recent call last):
# File "foo.py", line 27, in <module>
# con['foo'] += "what's going on?"
# AttributeError: Container instance has no attribute '__setitem__'
基本上,
con['foo'] += "what's going on?"
编译为以下内容:
item = con['foo']
item += "what's going on?"
conf['foo'] = item
您可以看到反编译代码,如下所示:
2 0 LOAD_GLOBAL 0 (con)
3 LOAD_CONST 1 ('foo')
6 DUP_TOPX 2
9 BINARY_SUBSCR
10 LOAD_CONST 2 ("what's going on?")
13 INPLACE_ADD
14 ROT_THREE
15 STORE_SUBSCR
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句