Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is self only a convention and not a real Python keyword?

Tags:

python

As far as I know, self is just a very powerful convention and it's not really a reserved keyword in Python. Java and C# have this as a keyword. I really find it weird that they didn't make a reserved keyword for it in Python. Is there any reason behind this?

like image 499
Terence Ponce Avatar asked Nov 09 '10 08:11

Terence Ponce


2 Answers

Because self is just a parameter to a function, like any other parameter. For example, the following call:

a = A()
a.x()

essentially gets converted to:

a = A()
A.x(a)

Not making self a reserved word has had the fortunate result as well that for class methods, you can rename the first parameter to something else (normally cls). And of course for static methods, the first parameter has no relationship to the instance it is called on e.g.:

class A:
    def method(self):
        pass

    @classmethod
    def class_method(cls):
        pass

    @staticmethod
    def static_method():
        pass

class B(A):
    pass

b = B()
b.method()        # self is b
b.class_method()  # cls is B
b.static_method() # no parameter passed
like image 200
Tim Delaney Avatar answered Nov 15 '22 22:11

Tim Delaney


Guido van Rossum has blogged on why explicit self has to stay: http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html

I believe that post provides some insight into the design decisions behind explicit self.

like image 32
Arlaharen Avatar answered Nov 15 '22 23:11

Arlaharen