[Tutor] Classes and "Self"

Kalle Svensson kalle@gnupung.net
Fri, 27 Apr 2001 16:04:27 +0200


Sez Mark A. Tobin:
> Hi there,
> I've been playing around with Python for a while now as my first real foray
> into programming.  I've just started looking at creating classes as they
> seem to be the more "mature" way to structure one's programming.  I can now
> implement instances and what not, thanks to some of the great tutorials out
> there, however I can't figure out what the "self" argument is all about.

Well, it is a reference to the instance that the method is run with.
An example:
>>> class C:
...     def f(self):
...         global i, j  # don't do this at home, kids... <wink>
...         if i is self:
...             print "self is i!"
...         elif j is self:
...             print "self is j!"
...         else:
...             print "self is not i or j!"
... 
>>> i = C(); j = C(); k = C() # create three instances of C
>>> i.f()
self is i!
>>> j.f()
self is j!
>>> k.f()
self is not i or j!
>>> C.f(i)  # check this one out...
self is i!

self is used to access the methods and data of the instance from inside its
own methods.  It is automatically passed as the first argument when a method
is sccessed from a class instace.  When the method is accessed from the
class, as in the last example, it's called an unbound method and the first
argument must be an instance of the class or a subclass.
I don't know if that helped at all, but it's a try.

Peace,
  Kalle
-- 
Email: kalle@gnupung.net     | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD
 [ Not signed due to lossage.  Blame Microsoft Outlook Express. ]