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

Piet van Oostrum piet at vanoostrum.org
Mon Sep 5 10:15:01 EDT 2011


Chris Torek <nospam at torek.net> writes:

[snip]
> Instead, we have a syntax where you, the programmer, write out the
> name of the local variable that binds to the first parameter.  This
> means the first parameter is visible.  Except, it is only visible
> at the function definition -- when you have the instance and call
> the instance or class method:
>
>     black_knight = K()
>     black_knight.meth1('a', 1)
>     black_knight.meth2(2)
>
> the first parameters (black_knight, and black_knight.__class__,
> respectively) are magic, and invisible.
>
> Thus, Python is using the "explicit is better than implicit" rule
> in the definition, but not at the call site.  I have no problem with
> this.  Sometimes I think implicit is better than explicit.  In this
> case, there is no need to distinguish, at the calls to meth1() and
> meth2(), as to whether they are "class" or "instance" methods.  At
> the *calls* they would just be distractions.

It *is* explicit also at the call site. It only is written at the left of the dot rather than at the right of the parenthesis. And that is necessary to locate which definition of the method applies. It would be silly to repeat this information after the parenthesis. Not only silly, it would be stupid as it would be a source of errors, and an example of DRY.
-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list