i don't really understand member variables..

Ian Bicking ianb at colorstudy.com
Wed Oct 23 23:17:08 EDT 2002


On Wed, 2002-10-23 at 19:54, gabor wrote:
> hi,
> 
> until now i thought i understand member variables...
> 
> but now i don't :-):
> 
> example:
> >>> class Test:
> ...     data = []
> ... 
> >>> a = Test()
> >>> a.data.append("x")
> >>> a.data
> ['x']
> >>> b = Test()
> >>> b.data
> ['x']
> 
> so they are shared?
> but now:
> 
> >>> b.data = ["y"]
> >>> b.data
> ['y']
> >>> a.data
> ['x']
> 
> now they aren't anymore....
> 
> so if i define some data after the class... line then those are static (
> as in c++?) but why the stop being static in the second code-example?

Someone else explained how you start with a class variable.  But there's
more, as you were able to see...

When you do an assignment like inst.var = something, and the instance
doesn't already have an instance variable by the name "var", then an
instance variable is created.  So when you did 'b.data = ["y"]', you
created a "data" instance variable in the b instance (but not in the a
instance).  So when you later say "a.data", it looks in a, finds no
instance variable, and then looks in Test, and finds a class variable. 
When you do "b.data" it finds an instance variable and returns that, and
never looks in Test.

If you want to change the class variable, you'd have to do Test.data =
["y"], or perhaps b.__class__.data = ["y"].  But of course if you do
something like b.data[0] = "y", you will be leaving the list in place,
and just changing it's 0th member -- so you'd never create an instance
variable with that statement.

This is all a little contorted.  My advice is to simply never assign to
class variables -- I usually use them as constants or as state-holding
objects (i.e., I never reassign the variable, but I might append to a
list).

  Ian





More information about the Python-list mailing list