function call questions

Frank Millman frank at chagford.com
Thu Oct 20 01:30:53 EDT 2016


wrote in message 
news:5506e4d8-bd1d-4e56-8d1b-f71fa8293393 at googlegroups.com...

在 2016年10月19日星期三 UTC+8下午3:17:18,Peter Otten写道:
> chenyong20000 at gmail.com wrote:
>
> > 在 2016年10月19日星期三 UTC+8上午11:46:28,MRAB写道:
> >> On 2016-10-19 03:15, chenyong20000 at gmail.com wrote:
> >> > Thanks Peter and Anssi for your kind help. Now I'm ok with the first
> >> > question. But the second question still confused me. Why "it seems 
> >> > that
> >> > after root = root.setdefault(ch,{}) tree['a'] and root are the same
> >> > object" and follows tree['a']['b']? Thanks.
> >> >

> please forgive my stupid. I still can't follow this.

Let's see if I can explain. I am using 't' and 'r' instead of 'tree' and 
'root', but otherwise it is the same as your original example.

>>> t = {}
>>> r = t
>>> id(t)
2542235910088
>>> id(r)
2542235910088

At this point, t and r are both references to the same empty dictionary.

>>> r = r.setdefault('a', {})

This has done two things.

It has inserted the key 'a' into the dictionary, and set its value to {}.

>>> t
{'a': {}}
>>> id(t)
2542235910088

It has also rebound 'r' so that it now references the new empty dictionary 
that has been inserted.

>>> r
{}
>>> id(r)
2542234429896
>>>t['a']
{}
>>> id(t['a'])
2542234429896

Now continue this process with r = r.setdefault('b', {}), and watch what 
happens.

Hopefully this will help you to understand. Feel free to ask further if not 
sure.

Frank Millman





More information about the Python-list mailing list