为什么在包含的项目中使用 __iadd__ 时,我的代码会生成 __setitem__ 错误? [英] Why does my code generate an __setitem__ error when using __iadd__ in contained item?

查看:34
本文介绍了为什么在包含的项目中使用 __iadd__ 时,我的代码会生成 __setitem__ 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么这段代码抱怨容器上没有 __setitem__ ?我以为我只需要容器上的 __getitem__ 来获取项目然后 __iadd__ 来设置值,不知道为什么它需要 __setitem__

Can anyone tell me why this code complains that there's no __setitem__ on container? I thought I only needed __getitem__ on the container to fetch the item and then __iadd__ to set the value, don't know why it's expecting __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

你可以看到,反编译代码,类似:

You can see, decompiling the code, something like:

  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        

这篇关于为什么在包含的项目中使用 __iadd__ 时,我的代码会生成 __setitem__ 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆