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

Michiel Overtoom motoom at xs4all.nl
Thu Sep 1 13:23:54 CEST 2011


> On Aug 31, 5:35 pm, "T. Goodchild" <tgoodch... at gmail.com> wrote:


>> So why is 'self' necessary on class methods?
>> 
>> Just curious about the rationale behind this part of the language.

When instance variables are accessed with the 'self.varname' syntax, it is clear to the programmer that an instance variable is accessed, and not some global.  Other languages have weird syntax conventions like that you have to prepend all instance attributes with an '@', and in languages like C++ where there is not necessarily such a syntactic requirement, many programmers use ad-hoc constructs like '_varname' or 'm_varname' to make the distinction clear.


>> 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.

Yes, you have a point there. My personal preference would be to optimize for the most common case, while exceptions to the norm are still possible, but perhaps a bit more verbose.

Greetings

-- 
"Learn to value yourself, which means: fight for your happiness."  - Ayn Rand      




More information about the Python-list mailing list