Why do class methods always need 'self' as the first parameter?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Aug 31 20:48:46 EDT 2011

Chris Torek wrote:

>>There are also static methods, which don't receive any special first
>>argument, plus any other sort of method you can invent, by creating
>>descriptors... but that's getting into fairly advanced territory. ...
> [rest snipped]
> I am not sure whether T. Goodchild was asking any of the above or
> perhaps also one other possible question: if an instance method
> is going to receive an automatic first "self" parameter, why require
> the programmer to write that parameter in the "def"?

Er, yes, just like I suggested in my opening paragraph, and as I answered
following the bit you marked as snipped :)

> For instance 
> we *could* have:
>     class K(object):
>         def meth1(arg1, arg2):
>             self.arg1 = arg1 # self is "magically available"
>             self.arg2 = arg2
>         @classmethod
>         def meth2(arg):
>             use(cls) # cls is "magically available"
> and so on.  This would work fine.  It just requires a bit of implicit
> sneakiness in the compiler: an instance method magically creates
> a local variable named "self" that binds to the invisible first
> parameter, and a class method magically creates a local variable
> named "cls" that binds to the invisible first parameter, and so
> on.

It would need more than "a bit", because methods are just wrappers around
functions. One way would be for Python to give that up, and require methods
to be special built-in types like functions. That adds complexity to the
compiler, and (very likely) would decrease the level of dynamism possible.

Another way would be for the compiler to perform darkest black magic to
determine whether the function was being called from inside a method or
not. That would be complicated and fragile.

> At the *definitions*, they are not as "distraction-y" since it is
> important to know, during the definition, whether you are operating
> on an instance (meth1) or the class itself (meth2), or for that
> matter on neither (static methods).  One could determine this from
> the absence or presence of "@classmethod" or "@staticmethod"

classmethod and staticmethod are functions, not declarations. You can't
assume that @classmethod is the only way to get a class method: the
metaclass could do it, or you could inject one in from the outside. You can
dynamically change the state of a method from instance method to class
method and back again at run-time.

Python classes have a lot of dynamism made possible by the fact that methods
are just wrappers around functions with an explicitly declared "self". That
dynamism is rarely used, but not *that* rarely, and is very useful when
used. Implicit self would likely negate all that.


More information about the Python-list mailing list