[Tutor] Self

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 26 Jul 2002 13:32:27 -0700 (PDT)


On Fri, 26 Jul 2002, Terje Johan Abrahamsen wrote:

> How does really the self thing work?

We can think of 'self' as the instance itself: we often use it as a
container to save our "own" state.



> Will these two examples actually work the same way, and is the only
> reason why one would use self is so one don't have to write the class
> name again and again?
>
> class smurf:
>     variable = 15
>
>     def write(self):
>         smurf.variable = smurf.variable + 1
>         print smurf.variable
>
> and:
>
>
> class smurf:
>     variable = 15
>
>     def write(self):
>         self.variable = self.variable + 1
>         print self.variable

No, they actually have subtly different behavior: the first will always
use the class's understanding of 'variable'.  So the write() method on a
smurf will always use the 'smurf.variable' to display.


The second case behaves like the first... at least initially, that is. As
soon as we call the write() method, the picture changes because of the
assignment to 'self.variable'.  From that point onward, a smurf instance's
idea of 'variable' diverges from the class --- it becomes part of the
individual instance's identity.



Let's do some stuff in the interpreter just to show what's going on with
the second smurf definition, because the second version is subtly tricky!
First, let's create two smurfs.

###
>>> papa = smurf()
>>> hefty = smurf()
>>> papa.variable
15
>>> hefty.variable
15
###

At the moment, both smurfs don't themselves have a customized 'variable'
in themselves, so they look up to the class's 'variable'.  Sorta like how
children look up to parents.

Any changes to the classes 'variable' will appear to affect 'papa' and
'hefty':

###
>>> smurf.variable = 42
>>> papa.variable
42
>>> hefty.variable
42
###


However, as soon as some instance assigns to itself, to it's
'self.variable', it becomes rebellious.  Hefty doesn't want to have his
'variable' tied up with that of all the smurfs: he wants independence, so
he keeps his own 'variable' close to his heart.

###
>>> hefty.variable = 'heart'
>>> papa.variable
42
>>> hefty.variable
'heart'
###


So 'self' is actually meant to keep the individual's state of mind: it's
meant to be able to distinguish instances from each other, while the class
definition tells us what the instances have in common.  That's how we can
distinguish the difference between 'smurf.variable' and 'hefty.variable'.


Hope this helps!