[Tutor] why "self" in methods?

Gonçalo Rodrigues op73418 at mail.telepac.pt
Mon Apr 5 15:57:45 EDT 2004


Em Mon, 5 Apr 2004 18:12:21 +0100, "Alan Gauld"
<alan.gauld at blueyonder.co.uk> atirou este peixe aos pinguins:

>> Also, about the self controversy, think about nested definitions
>> of classes. You get into trouble with the implicit self thingy.
>
>Really? How so? Surely that's merely a matter of scoping.
>I agree that self being explicit is "a good thing" but
>it is not necessary, other languages seem to manage quite
>well without it.
>

[Answering also to Marylin Davis]

Suppose that self was a keyword naming the implicit object that's
passed to methods. Consider the following example:

class Outer(object):
    def amethod(arg):
        class Inner(object):
            def amethod(arg):
                self.arg = arg #What's self here?
        return inner()

Is self from the inner or from the outer? The "logical" answer would
be from the inner amethod from the Inner class. But then the outer
self is shadowed -- not good. And since it's implicit... you know
where I'm getting at.

Explicit is better than implicit. And although from the top of my head
I can't remember a use case of unbound methods, *I have used them*
several times. Suppose there were no unbound methods, what should be

class Outer(object):
    def amethod(arg):
         ....

Outer.amethod

If methods are attributes of the class object, then the above must
return something sensible. And if it is to remain callable, well, it
must receive the instance explicitely as a parameter. Perhaps you
could write some wrappers, etc. that would do this for you, but
somehow I think that without the explicit self it would not be very
elegant. Besides, it gives a very handy syntax for calling a super
class method that is overriden.

Also in class methods, in meta methods, etc. the explicit self allows
me to call the self, cls, that is


class Outer(object):
    def method(cls):
        ....
    method = classmethod(method)

which IMHO is much better from a raedability point of view

Read the FAQ entry on this for a couple more reasons.

So, my verdict is definitely: explicit self is a *very good* Python
feature and a clear mark of excellent design. And to the stake with
the blasphemers that dare oppose the BDFL :-)

With my best regards,
G. Rodrigues



More information about the Tutor mailing list