[Tutor] confused: classes containing dicts
Calum Mackay
calum.mackay at cdmnet.org
Sat Oct 9 04:04:21 CEST 2004
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.
cheers,
c.
More information about the Tutor
mailing list