[Tutor] multiple class instances

Arne Mueller a.mueller@icrf.icnet.uk
Mon, 10 May 1999 15:56:32 +0100


Hi,

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.

You've to use instance members using the 'self' phenomena ... ;-) . Self
refers to the created instance object and not to the class, see below
...

K P wrote:
> 
> How can I create multiple class instances (objects?) that do not share
> the same data? For example the following class:
> 
> class Spam:
>         choice = "I\'ll have the spam"
> 
> if I create an instance:
> 
> spam1 = Spam
> 
> Then reassign a data member:
> 
> spam1.choice = "Do you have anything besides spam?"
> 
> Then create a new instance:
> 
> spam2 = Spam
> 
> Then print spam2.choice, it will print the value assigned above:
> 
> spam2.choice
> 'Do you have anything besides spam?'
> 

Here's some input/output of interactive python:

python> class Spam:
...     def __init__(self):
...             self.choice = "I\'ll have the spam"
... 
python> spam1 = Spam()
python> spam1.choice = "Do you have anything besides spam?"
python> spam1.choice
'Do you have anything besides spam?'
python> spam2 = Spam()
python> spam2.choice
"I'll have the spam"

The __init__ function is the constructor of the object which is called
when an object is created from class Spam. Each Onject gets it's own
member 'choice', mofying 'choice' changes the instance member and not
the class.

Interanlly the class spam1.choice is translated into: choice(spam1),
where spam1 is a reference to the object with name 'spam1' - so it's an
unique object in the universe. 

Browese the FAQ for 'self' and you'll find lots of interesting
information about how it works ...

	Greetings,

	Arne