Class initialization
Tim Harig
usernet at ilthio.net
Sun Aug 8 11:55:09 EDT 2010
On 2010-08-08, Tim Harig <usernet at ilthio.net> wrote:
> On 2010-08-08, Tim Harig <usernet at ilthio.net> wrote:
>> 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.
>
> Maybe I can make that a little clearer yet. When you define a class in
> python you actually create a class object. This object is basically used
> as a template to create instance objects. When you define a variable
> attached to the class object that is mutable, the instance objects receive
> the exact same reference that was given to the instance object. Since it
> is mutable, any changes made using that reference will affect all of the
> instances that also point to that reference. You wouldn't have seen this
> effect using your simplified examle because number are immutable objects.
> When you change the value for one of the instance objects, it receives a
> new reference, rather then making the change in place. The other instances
> do not reflect this change because their variables still point back to the
> original reference given to the class.
And to complete that thought, when you assign variables directly to
the instance, as I did using the constructor's reference to self, each
instance receives a brand new reference that is not shared among any of
the other instances.
More information about the Python-list
mailing list