The need to put "self" in every method

D H d at e.f
Mon Jun 13 22:46:03 EDT 2005


Steve Holden wrote:
> Fernando M. wrote:
> 
>> Hi,
>>
>> i was just wondering about the need to put "self" as the first
>> parameter in every method a class has because, if it's always needed,
>> why the obligation to write it? couldn't it be implicit?
>>
>> Or is it a special reason for this being this way?
>>
>> Thanks.

One reason is because of the dynamic nature of Python classes.  You can 
attach new methods to a class after it is instantiated, or remove 
methods.  The language boo (http://boo.codehaus.org/) has classes 
defined at compile time, and there "self" is not needed at all.  If you 
want to use the duck typing features in boo, however, and re-implement 
python-like dynamic classes that can have methods removed or added at 
any time, then your methods need some kind of "self" parameter so they 
can access the context of their class instance, because really there is 
no special relationship between the methods and the class unless you 
explicitly specify it.

> The reason can be found in the output from the python statement "import 
> this". Explicit is better than implicit.

Like those invisible yet explicit scope indicators, tabs and spaces.



More information about the Python-list mailing list