[Tutor] Tutor digest, Vol 1 #539 - 13 msgs

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 10 Jan 2001 14:09:59 +0100


On Wed, Jan 10, 2001 at 07:51:05AM -0500, Sharriff Aina wrote:
> Can someone explain exactly why I have to add "self" to a class function
> that Ive defined?
> 
> class blah:
>     "the new class"
>     def myfunction(self):
>         print "Hello Class"
> 
> the below code would not work:
> 
> 
> class blah:
>     "the new class"
>     def myfunction():
>         print "Hello Class"

That's the way it works in Python. Methods get the instance they belong
to as their 1st argument, so that they can reach its variables.

class blah:
   def __init__(self):
      self.name = "bla"
      
The init function uses the 'self' argument to set the variable 'name' in
this instance.

The name 'self' is not mandatory, but everybody uses it so you should
as well :).

Pure *class functions*, functions in a class not belonging to any instance,
do not exist in Python. The convention is to make them normal functions,
outside the class. It can be argued that when a class function does
something that's not tied to any instance of the class, then it shouldn't
be in that class at all.

-- 
Remco Gerlich