gpt4 book ai didi

python - 为什么我的代码在包含的项目中使用 __iadd__ 时会生成 __setitem__ 错误?

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:09 29 4
gpt4 key购买 nike

谁能告诉我为什么这段代码提示容器上没有 __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

关于python - 为什么我的代码在包含的项目中使用 __iadd__ 时会生成 __setitem__ 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24875077/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com