[Tutor] multiple class instances

Corran Webster Corran.Webster@math.tamu.edu
Mon, 10 May 1999 09:43:43 -0500 (CDT)


> How can I create multiple class instances (objects=3F) that do not share 
> the same data=3F For example the following class:
> 
> class Spam:
> 	choice =3D "I\'ll have the spam"

I suspect that you're thinking in C++ terms here - Python is much more
dynamic, so the correct place to create instance data is in the __init__
method as follows:

class Spam:
  def __init__(self):
    self.choice = "I'll have the spam."

spam1 = Spam()
spam1.choice = "Do you have anything besides spam?"
spam2 = Spam()

print spam1.choice, spam2.choice
 
> if I create an instance:
> 
> spam1 =3D Spam

Note that you aren't creating a class instance here - you're creating
another reference to the Spam class.  This is probably adding another
level of confusion for you.  What your code was doing was:

* creating a class with a class variable "choice"
* creating another reference to the class
* changing the value of the class variable
* creating a new reference to the class

Note that there's only once class here, no instances, and only one variable
which just has different names ("Spam.choice", "spam1.choice" and 
"spam2.choice").

Hope that this helps you understand Python classes a bit better.

Corran