Unclear On Class Variables

Fredrik Lundh fredrik at pythonware.com
Thu Jan 13 10:01:48 EST 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.
> 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.

"set" as in:

    obj = foo()
    obj.x = 10 # set x

?

if so, the "obj.x=" line is *adding* an instance variable to the "x" object, which will
then hide the "x" at the class level.

>>> class foo(object):
...     x = 0
...     y = 1
...
>>> obj = foo()
>>> obj.__dict__
{}
>>> obj.x
0
>>> obj.y
1
>>> foo.x
0
>>> obj.x = 10
>>> obj.__dict__
{'x': 10}
>>> obj.x
10
>>> foo.x
0

if you want to assign to the class variable, assign to the class variable:

>>> obj = foo()
>>> obj.x
0
>>> foo.x = 20
>>> obj.__dict__
{}
>>> obj.x
20
>>> foo().x
20

</F> 






More information about the Python-list mailing list