The need to put "self" in every method

Piet van Oostrum piet at cs.uu.nl
Tue May 31 17:28:17 EDT 2005


>>>>> "Fernando M." <fernandomirandamuro at gmail.com> (FM) wrote:

>FM> Hi,
>FM> i was just wondering about the need to put "self" as the first
>FM> parameter in every method a class has because, if it's always needed,
>FM> why the obligation to write it? couldn't it be implicit?

>FM> Or is it a special reason for this being this way?

There is.
Inside a method there are 3 kinds of identifiers:
- local ones e.g. parameters and local variables
- global ones (actually module-level)
- instance variables and methods

Because Python has no declarations there must be a different way to
indicate in which category an identifier falls. For globals it is done with
the 'global' keyword (which actually is a declaration), for instance
variables the dot notation (object.name) is used and the rest is local.
Therefore every instance variable or instance method must be used with the
dot notation, including the ones that belong to the object `itself'. Python
has chosen that you can use any identifier to indicate the instance, and
then obviously you must name it somewhere. It could have chosen to use a
fixed name, like 'this' in Java or C++. It could even have chosen to use a
keyword 'local' to indicate local ones and let instance ones be the
default. But if instance variable would be implicit, local ones should have
been explicit.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list