On 13 Jan 2005 07:18:26 EST, Tim Daneliuk <[EMAIL PROTECTED]> 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,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to