class attribute confusion
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Dec 3 17:58:46 EST 2010
On Fri, 03 Dec 2010 22:54:19 +0100, OAN wrote:
> Hi,
>
> i was having a problem with class attributes initiated outside of
> __init__. This code is a demonstration of what i mean:
[...]
> I would expect the following result:
>
> v: [1]
> x: [1, 2]
> y: [1, 2]
> z: [1]
> v: [1]
>
> Who wouldn't, right?
Everybody who actually understands Python's object model.
> The four variables v,x,y and z now actually share the same 'mylist'!! To
> get the correct results, i have to initialize 'mylist' inside of the
> __init__ method!
Right. If you define a *class* attribute, it lives in the class, not the
instance, and so all instances share the same value.
> I think this behaviour is totally wrong, since it seems A.__init__(self)
> is changing the value inside of A() not inside of the object variable
> 'self' (that should be x or y)!!
A.__init__(self) calls A's init method with self (either x or y) as the
self parameter, but A's init method merely modifies the class attribute
mylist in place. It doesn't create a new list.
The behaviour you're seeing is no different from this:
shared = []
a = {"spam": shared, "ham": 23}
b = {"spam": shared, "ham": 42}
a["spam"].append("parrot")
What would you expect the value of b["spam"] to be?
--
Steven
More information about the Python-list
mailing list