reason/history of self

Martijn Faassen m.faassen at vet.uu.nl
Wed Jan 16 08:25:15 EST 2002


gabor farkas <xlat at pobox.sk> wrote:
> what was the name of that thread?

> i could only find the thread "History of 'self' and why not at least 'my'?" 
> but there they talk about the problem that in a method you have to write 
> "self." to access a local variable... 

> i'm talking about having to write self in the method definition like in "def 
> mymethod(self)"...

Because there isn't that much of a difference between methods and 
functions in the first place, and Python just makes that clear.

class EmptyClass:
    pass

def myfunction(self, a):
    return self.value + a

o = EmptyClass()
o.value = 1
print myfunction(o, 2) # prints 3

is almost equivalent to:

class Class:
    def mymethod(self, a):
        return self.value + a

o = Class()
o.value = 1
print o.mymethod(2) # prints 3

Except that in the latter 'self' is passed implicitly (it being whatever
o refers to), and you can exploit dynamic typing more easily.

You could use 'foo' instead of 'self' in both cases; Python doesn't treat
the word 'self' in any special way; it just passes the object
a method is called on as the first argument to that method. There is
a very strong convention that the first argument there is called 'self'. :)

So, there isn't really much magic going on at all. The main magic is
that 'self' is passed implicitly and not explicitly in the case of
objects. More magic is that things like this are also possible 
(very useful):

foo = o.mymethod
foo()

'o' gets automatically bound here to 'mymethod' so you that when you call
foo later 'o' gets passed implicitly.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list