tags:

views:

986

answers:

6

When defining a method on a class in Python, it looks something like this:

class MyClass(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype.

Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?

A: 

Some discussion about self can be found in this mailing list thread.

ctcherry
+10  A: 

It's to minimize the difference between methods and functions. It allows you to easily generate methods in metaclasses, or add methods at runtime to pre-existing classes.

e.g.

>>> class C(object):
...     def foo(self):
...         print "Hi!"
...
>>>
>>> def bar(self):
...     print "Bork bork bork!"
...
>>>
>>> c = C()
>>> C.bar = bar
>>> c.bar()
Bork bork bork!
>>> c.foo()
Hi!
>>>

It also (as far as I know) makes the implementation of the python runtime easier.

Ryan
+13  A: 

I like to quote Peters' Zen of Python. "Explicit is better than implicit."

In Java and C++, 'this.' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.

Python elects to make things like this explicit rather than based on a rule.

Additionally, since nothing is implied or assumed, parts of the implementation are exposed. self.__class__, self.__dict__ and other "internal" structures are available in an obvious way.

S.Lott
Although it would be nice to have a less cryptic error message when you forget it.
Martin Beckett
You can spell it anything (my, this, whatever) and for certain type of class methods, it changes meaning. Not easy to work out your intent and give a "better" message.
S.Lott
A: 

There is also another very simple answer: according to the zen of python, "explicit is better than implicit".

Flávio Amieiro
+2  A: 

Python doesn't force you on using "self". You can give it whatever name you want. You just have to remember that the first argument in a method definition header is a reference to the object.

Victor Noagbodji
By convention, it should however be 'self' for instances or 'cls' where types are involved (mmmm metaclasses)
pobk
+7  A: 

I suggest that one should read Guido van Rossum's blog on this topic - Why explicit self has to stay.

bhadra