Unclear On Class Variables

Steve Holden steve at holdenweb.com
Thu Jan 13 15:50:12 CET 2005


Tim Daneliuk wrote:

> I am a bit confused.  I was under the impression that:
> 
> class foo(object):
>     x = 0
>     y = 1
> 
> means that x and y are variables shared by all instances of a class.

What it actually does is define names with the given values *in the 
class namespace*.

> But when I run this against two instances of foo, and set the values
> of x and y, they are indeed unique to the *instance* rather than the
> class.
> 
I imagine here you are setting instance variables, which then *mask* the 
presence of class variables with the same name, because "self-relative" 
name resolution looks in the instance namespace before it looks in the 
class namespace.

> It is late and I am probably missing the obvious.  Enlightenment 
> appreciated ...

You can refer to class variables using the class name explicitly, both 
within methods and externally:

  >>> class X:
  ...   count = 0
  ...   def getCt(self):
  ...     return self.count
  ...   def inc(self):
  ...     self.count += 1
  ...
  >>> x1 = X()
  >>> x2 = X()
  >>> id(x1.count)
168378284
  >>> x1.inc()
  >>> id(x1.count)
168378272
  >>> id(x2.count)
168378284
  >>> id(X.count)
168378284
  >>> x1.getCt()
1
  >>> x2.getCt()
0
  >>>

regards
  Steve
-- 
Steve Holden               http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
Holden Web LLC      +1 703 861 4237  +1 800 494 3119




More information about the Python-list mailing list