yeeha
yeeha

Reputation: 138

python dict attribute and items

In following python code, what is the difference between dict.setitem and setattr ?

when I comment the setattr statement, I cannot run g.abcd. But if I keep the setattr statement, I can run both g.abcd and g['abcd'], which return the same value 300

id(g.abcd) and id(g['abcd']) returns the same value.

I am confused: dict.setitem should insert a hash pair into the hash table. setattr should add an extra attributes (or field, or member) to class dict. so they seem to be different thing. Therefore I think it is expected that eliminating setattr will fail 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?

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

Upvotes: 0

Views: 583

Answers (1)

kindall
kindall

Reputation: 184151

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?

Upvotes: 2

Related Questions