[Tutor] confused: classes containing dicts

Bob Gailer bgailer at alum.rpi.edu
Sat Oct 9 04:17:25 CEST 2004


At 08:04 PM 10/8/2004, Calum Mackay wrote:
>Kent Johnson wrote:
>>The first few pages of chapter 21 of Learning Python talk about this a 
>>little.
>
>Having re-read it, I'm not sure it doesn't perpetuate my confusion.
>
>They use the example:
>
>class SharedData:
>     spam = 42
>
>x = SharedData()
>y = SharedData()
>
>and then note that references:
>
>x.spam, y.spam, SharedData.spam
>
>all give the same value. Also, if SharedData.spam is changed, then 
>references of x.spam, y.spam see that change.
>
>However, it then goes onto note that if x.spam is changed, x.spam attaches 
>a name to x itself. i.e:
>
>x.spam = 88
>
>and y.spam, SharedData.spam still give 42.
>
>This is not what happens with dicts, at least in my example:
>
>class SharedData:
>     l = {}
>
>x = SharedData()
>
> >>> x.l["a"] = 123
> >>> x.l
>{'a': 123}
> >>> SharedData.l
>{'a': 123}
>
>Here, assignment to x *has* changed the attr in the class, unlike the 
>following:
>
> >>> x = SharedData()
> >>> x.l
>123
> >>> x.l = 456
> >>> x.l
>456
> >>> SharedData.l
>123
>
>There's a difference in behaviour here, depending on whether the attribute 
>is an int or a dict.

No - there is a difference in the target of the assignment:
 >>> x.l = 456 is an assignment to attribute l of instance x. SInce the 
instance attribute did not exist, it is created.
 >>> x.l["a"] = 123 is an assignment to a key in the dictionary x.l, not to 
the attribute x.
HTH

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 



More information about the Tutor mailing list