Class initialization

Tim Harig usernet at ilthio.net
Sun Aug 8 11:28:32 EDT 2010


On 2010-08-08, Costin Gament <costin.gament at gmail.com> wrote:
> So you're saying I should just use __init__? Will that get me out of
> my predicament?
> No, I don't quite understand the difference between my exemple and
> using __init__, but I will read the docs about it.

It is not so much using __init__() that makes the difference as it what
scope the variables are assigned to.  If you define them as you where, then
the variables are associated with the class object itself.  If the variable
is a mutable type, and you change it in one instance, it actually changes
it in the class object which means it also changes for all of the
instances.

I used the constructor because it gives me a reference to the newly created
instance object "self".  I then assign the variables to self, which
assignes them to the newly created instance object.  Then each instance has
its own separate a and b variables that will not change when the variables
are changed inside of another instance object.



More information about the Python-list mailing list