Why do you need explicitly have the "self" argument in a Python method? Why do you need explicitly have the "self" argument in a Python method? python python

Why do you need explicitly have the "self" argument in a Python method?


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.


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.


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

When a method definition is decorated, we don't know whether to automatically give it a 'self' parameter or not: the decorator could turn the function into a static method (which has no 'self'), or a class method (which has a funny kind of self that refers to a class instead of an instance), or it could do something completely different (it's trivial to write a decorator that implements '@classmethod' or '@staticmethod' in pure Python). There's no way without knowing what the decorator does whether to endow the method being defined with an implicit 'self' argument or not.

I reject hacks like special-casing '@classmethod' and '@staticmethod'.