Unclear On Class Variables

Simon Brunning simon.brunning at gmail.com
Thu Jan 13 07:41:39 EST 2005


On 13 Jan 2005 07:18:26 EST, Tim Daneliuk <tundra at tundraware.com> 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.

I can see why you might think that:

>>> class Spam(object):
... 	eggs = 4
... 
>>> spam = Spam()
>>> spam2 = Spam()
>>> spam.eggs
4
>>> spam2.eggs
4
>>> spam.eggs = 2
>>> spam.eggs
2
>>> spam2.eggs
4

But you are being mislead by the fact that integers are immutable.
'spam.eggs = 2' is *creating* an instance member - there wasn't one
before. Have a look at what happens with a mutable object:

>>> class Spam(object):
... 	eggs = [3]
... 
>>> spam = Spam()
>>> spam2 = Spam()
>>> spam.eggs
[3]
>>> spam2.eggs
[3]
>>> spam.eggs.append(5)
>>> spam.eggs
[3, 5]
>>> spam2.eggs
[3, 5]

-- 
Cheers,
Simon B,
simon at brunningonline.net,
http://www.brunningonline.net/simon/blog/



More information about the Python-list mailing list