[Tutor] **kw and self

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 21 Jun 2001 10:44:57 +0200


On  0, Willi Richert <w.richert@gmx.net> wrote:
> do I have special features with this "self" or is it just because of Python's
> design? Java and the like don't have self as an implied argument.

This is just the way Python was designed.

In Python, if you assign to a variable, it's always a local variable, or a
module global if you said so with 'global x' for variable x.

So if you want to assign to something in another namespace (like an instance
variable), you have to explicitly write that: self.x = 3.

Python passes the instance as the first argument of a method. How else could
the local variable 'self' get a value?

So if we have a class:

class Spam:
   def some_method(self):
      # If this method is called on an instance, 'self' will refer to the
      # instance. Therefore, we can use it to set the instance variable 'x':
      self.x = 3

instance = Spam()
instance.somemethod()
print instance.x # Prints 3.

In Python, as much as possible, nothing 'magical' happens, everything must
be as explicit as possible. This improves readability.

Since 'self' is just a variable name, you could use any other name for it as
well, but everyone uses 'self'.

-- 
Remco Gerlich