understaning "self"

Nicola Musatti nicola.musatti at gmail.com
Thu Feb 21 12:48:40 EST 2008


On Feb 21, 2:34 pm, "Poppy" <znfmail-pythonl... at yahoo.com> wrote:
> I've been searching online to try get a better understanding of what "self"
> does when I define this parameter in my class functions. All I'm finding is
> debates on whether  "self" has any value to the language but that doesn't
> help me in my newbie question. So the code excerpt below is from "Beginning
> Python" Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, Parker,
> and Roberts.
>
> What I think "self" is doing is limiting the function call to only function
> in "this" class. So in the function below "has" calls self.has_various(), if
> I had a function called "has_various" in my program or another included
> class using "self" insures that the "has_various" below is the one used. Am
> I correct in my understanding?

I'll try to explain with as simple an example as I can think of. First
of all, 'self' is just a conventional name, it isn't a keyword and has
no special meaning per se. You could just as easily write:

In [10]: class A(object):
   ....:     def __init__(this, n):
   ....:         this.n = n
   ....:
   ....:     def f(me):
   ....:         print me.n
   ....:
   ....:

In [11]: a = A(42)

In [12]: a.f()
42

The point is that when you write a statement such as

a.f()

the interpreter uses 'a' in two ways: first, to find which function
f() to call; second, as a parameter to f() itself. The conventional
'self' helps you remind that the first argument is going to be the
instance of the class on which the function f() is going to be called.

You can actually separate the two uses above with the following
equivalent call:

In [13]: A.f(a)
42

Here you tell the interpreter which function f() to call by specifying
its class, A, and you pass it 'a' explicitly as an argument.

One could argue that the C++/Java/C# approach where you don't specify
the current instance as an argument, but can optionally use the 'this'
keyword to refer to it is more convenient; however the explicit 'self'
makes it possible for free functions and class methods to work in
exactly the same way. This in turn makes the language more consistent
and makes some more advanced, very effective techniques possible.

Hope this helps.

Cheers,
Nicola Musatti



More information about the Python-list mailing list