Why do class methods always need 'self' as the first parameter?
johnroth1 at gmail.com
Thu Sep 1 14:45:36 CEST 2011
On Aug 31, 8:35 am, "T. Goodchild" <tgoodch... at gmail.com> wrote:
> I’m new to Python, and I love it. The philosophy of the language (and
> of the community as a whole) is beautiful to me.
> But one of the things that bugs me is the requirement that all class
> methods have 'self' as their first parameter. On a gut level, to me
> this seems to be at odds with Python’s dedication to simplicity.
> For example, consider Python’s indent-sensitive syntax. Although
> other languages didn’t use indentation to specify scope, programmers
> always used indentation anyways. Making indentation took a common
> practice, made it a rule, and the result was a significantly improved
> signal-to-noise ratio in the readability of Python code.
> So why is 'self' necessary on class methods? It seems to me that the
> most common practice is that class methods *almost always* operate on
> the instance that called them. It would make more sense to me if this
> was assumed by default, and for "static" methods (methods that are
> part of a class, but never associated with a specific instance) to be
> labelled instead.
> Just curious about the rationale behind this part of the language.
I personally consider this to be a wart. Some time ago I did an
implementation analysis. The gist is that, if self and cls were made
special variables that returned the current instance and class
respectively, then the compiler could determine whether a function was
an instance or class method. If it then marked the code object
appropriately you could get rid of all of the wrappers and the
attendant run-time overhead.
I've never published the analysis because that train has already left
the shed. The earliest it could be considered would be 4.0, which
isn't even on the horizon.
More information about the Python-list