[Tutor] multiple class instances

Corran Webster cwebster@math.tamu.edu
Mon, 10 May 1999 10:48:34 -0500 (CDT)


> THere are two different types of members:
> 
> 1. Class members
> 2. Instance or object members
> 
> You use class members which means when creating an instance of class
> Spam and assigning 'I\'ll have the spam' to it's choice member you
> modify the choice in the CLASS your instance is made from not the
> instance itself. So when creating a second instance it is based on the
> 'modified' Spam class.

What you've written isn't correct:

Python 1.5.2 (#2, Apr 15 1999, 13:12:41)  [GCC 2.7.2] on sunos5
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> class Spam:
...   choice = "I'll have the spam"
... 
>>> spam1 = Spam()
>>> spam1.choice = "Wibble"
>>> spam2 = Spam()
>>> print spam2.choice
I'll have the spam
>>> print spam1.choice
Wibble
>>> print Spam.choice
I'll have the spam
>>> Spam.choice = "Do you have anything besides spam?"
>>> print spam2.choice
Do you have anything besides spam?

What happens when you have a class variable and attempt to change it in
the manner "instance.var = whatever" is that you create a new instance
variable with the new value - the class variable remains unchanged.

IOW, you can access a class variable's value as "instance.var", but you
can't change the value like that.

Ken's problem was compounded by the fact that he wasn't using instances
anywhere - notice the parentheses were missing from the "spam1 = Spam"
command inthe original code.

For people learning python, note that the above sort of trick really
obfuscates your code and makes it likely to have hard-to-find errors -
if you are using a class variable you should (almost[1]) always refer to
it as "class.var" to avoid confusion.

Corran

[1] Technically methods in Python are special cases of class variables,
but you always refer to them as "instance.method" so that you get
appropriate behavior.  And there can be cases where this sort of
behaviour is precisely what you want, but it's magic and confusing, so
probably not best for beginners.