What is the "self" name always referring to...?

John E. Barham jbarham at jbarham.com
Wed Dec 10 02:04:24 EST 2003


"Todd Gardner" wrote:

> Where can I go to find more information about the "self" argument?

>From the Python tutorial:

"Conventionally, the first argument of methods is often called self. This is
nothing more than a convention: the name self has absolutely no special
meaning to Python. (Note, however, that by not following the convention your
code may be less readable by other Python programmers, and it is also
conceivable that a class browser program be written which relies upon such a
convention.) "

http://www.python.org/doc/current/tut/node11.html#SECTION0011400000000000000000

> Is there something special about the word "self" or did Mr. Guido van
> Rossum just decide to us the word arbitrarily?

You could use anything, but the convention for using "self" is very strong.

> More precisely it seems that most all classes have "self" as the first
> parameter.  This may be directly obvious but is the word "self" always
> referring to the class or the function it is used in?

I'm not sure what you're asking here.  The first argument of any class
method (i.e., "self" per the above discussion) is the object on which the
method is being called.  It's equivalent to the "this" keyword in C++
(Java?), although in C++ "this" is implied and is not part of the argument
list.

A contrived example:

C++:

class Foo {
public:
    Foo(int a)
    {
        a_ = a;
        this->a_ = a; // same as above
    }

    int getA() { return a_; }

private:
    int a_;
};

Python:

class Foo:
    def __init__(self, a):
        self._a = a

    def getA(self):
        return self._a


> Is it a reserved word?

No.

> Thank you in advance,

Sure.

    John






More information about the Python-list mailing list