[Tutor] Self

Sean 'Shaleh' Perry shalehperry@attbi.com
Fri, 26 Jul 2002 13:20:55 -0700 (PDT)


On 26-Jul-2002 Terje Johan Abrahamsen wrote:
> How does really the self thing work?
> 
> 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
> 

'variable' in this case belongs to the *CLASS* not the *INSTANCE*.

>>> s = smurf()
>>> other = smurf()
>>> s.write()
16
>>> other.write()
17


this is why smurf.variable works.  You are referencing a global class variable.

> and:
> 
> class smurf:
>     variable = 15
> 
>     def write(self):
>         self.variable = self.variable + 1
>         print self.variable
> 
> Is there any reason why to use the first over the second or opposite? And, 
> in the first one, why do I have to write the self in 'def write(self):', or 
> don't I have to?
> 

since self will refer to an instance of class this works just like above. 
However:

class smurf:
  def __init__(self):
    self.variable = 15

  def write(self):
    smurf.variable = smurf.variable + 1
    print smurf.variable

will fail.  You need to define 'write' as:

def write(self):
  self.variable = self.variable + 1
  print self.variable

and now

s = smurf()
s.write()
16
other = smurf()
other.write()
16