[Tutor] multiple class instances

Corran Webster cwebster@math.tamu.edu
Mon, 10 May 1999 12:05:36 -0500 (CDT)


On 10 May, Deirdre Saoirse wrote:
> On Mon, 10 May 1999, Corran Webster wrote:
> 
>> 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."
> 
> It's only necessary to create it in __init__ if it's necessary for the
> instantiation of the class. Otherwise, it can be done in any method with
> the self directive. (I'm more from the C++ school where you'd write a
> method to fuss with any variables rather than manipulating them directly
> outside the class definition)

Perhaps "correct" was the wrong word - let's just say that the standard
Python idiom is to intialise instance variables in the __init__ method.
You are of course correct in pointing out that instance variables can
be created in any method - in fact they can be created anywhere.  For
the tutees:

spam1 = Spam()
spam1.choice2 = "A new instance variable"

will create an instance variable in spam1.  But no other instance of
Spam will even know of its existence.  This can be confusing for people
used to languages which use declarations heavily.

I'd argue that with python, writing accessor functions is often
overkill - particularly given that there is only weak data-hiding and
protection available.  A determined programmer can always mess with
your classes and instances.  For things like validation/sanity checking
of values for variables, there is of course a case for accessors in
python.

Corran