简体   繁体   English

python dict属性和项目

[英]python dict attribute and items

In following python code, what is the difference between dict.setitem and setattr ? 在下面的python代码中,dict.setitem和setattr有什么区别?

when I comment the setattr statement, I cannot run g.abcd. 当我评论setattr语句时,无法运行g.abcd。 But if I keep the setattr statement, I can run both g.abcd and g['abcd'], which return the same value 300 但是,如果我保留setattr语句,则可以同时运行g.abcd和g ['abcd'],它们返回相同的值300

id(g.abcd) and id(g['abcd']) returns the same value. id(g.abcd) and id(g['abcd'])返回相同的值。

I am confused: dict.setitem should insert a hash pair into the hash table. 我很困惑:dict.setitem应该在哈希表中插入一个哈希对。 setattr should add an extra attributes (or field, or member) to class dict. setattr应该为类dict添加一个额外的属性(或字段或成员)。 so they seem to be different thing. 所以他们似乎是另一回事。 Therefore I think it is expected that eliminating setattr will fail g.abcd. 因此,我认为消除setattr将会失败g.abcd。

But I don't understand why id() returns the same value for g.abcd and g['abcd'], why they refer to the same thing/location in the memory? 但是我不明白为什么id()为g.abcd和g ['abcd']返回相同的值,为什么它们在内存中引用相同的事物/位置?

thx 谢谢

class T(dict):

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)   #  <-------  dict.setitem
        setattr(self, key, value)                 #  <-------- setattr


g=T()
g.__setitem__('abcd', 300)

>>> id(g.abcd)

147169236

>>> id(g['abcd'])

147169236

Because you store the same object in both cases. 因为在两种情况下都存储相同的对象。 So, when you retrieve it, you are getting the same object regardless of which way you get it. 因此,当您检索它时,无论使用哪种方式获取它,都将得到相同的对象。 How could it be any other way? 怎么可能是其他方式呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM