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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Aug 31 18:06:50 CEST 2011


John Gordon wrote:

> In <0dc26f12-2541-4d41-8678-4fa53f347acf at g9g2000yqb.googlegroups.com> "T.
> Goodchild" <tgoodchild at gmail.com> writes:
> 
>> 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.
> 
> How would a method access instance variables without 'self'?

If Python had compile time declarations, the compiler could know whether x=1
was referring to a local variable x or an attribute x.

The reader might not, but the compiler would :)


By the way, although the Python docs are a little inconsistent, the usual
term here is "attribute" rather than "instance variable". 

Attributes need not live on the instance: they can also live on the class, a
superclass, or be computed at run-time via at least three different
mechanisms I can think of (__getattribute__, __getattr__, properties).
Local variables are treated a bit differently from attributes, but broadly
speaking, if you need a dot to access something, it's an attribute, if you
don't, it's a name binding (or variable).

Python even has two different sorts of errors for "variable" lookup
failures: NameError (or UnboundLocalError) for un-dotted names, and
AttributeError for dotted names.


> They probably could have made 'self' a magical attribute that just
> appears out of thin air instead of being passed as an argument, like
> 'this' in C++.  But would that really provide any benefit?

Well obviously the C++ people thought so :)

The effort to type "self, " in method signatures is pretty low. I don't
think it is a problem. But other languages are free to choose differently.
Cobra, for example, is explicitly derived from Python in many ways, but it
drops the "self" (as well as other changes).

http://cobra-language.com/docs/python/



-- 
Steven




More information about the Python-list mailing list