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

Piet van Oostrum piet at vanoostrum.org
Thu Sep 8 01:01:07 CEST 2011

"Prasad, Ramit" <ramit.prasad at jpmorgan.com> writes:

> It seems to me that if I add a function to the list of class attributes it will automatically wrap with "self" but adding it to the object directly will not wrap the function as a method. Can somebody explain why? I would have thought that any function added to an object would be a method (unless decorated as a class method). 

The special magic to transform a function into a method is only applied
for functions found as attributes of the class, not for instance
attributes. It is a matter of design.

> Hmm, or does the decoration just tell Python not to turn an object's function into a method? I.e. Is the decorator basically just the syntactic sugar for doing the above?

The classmethod decorator transforms the method (or actually the
function) into a different kind of object (a class method). 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]

More information about the Python-list mailing list