[Tutor] why "self" in methods?

Gonçalo Rodrigues op73418 at mail.telepac.pt
Tue Apr 6 05:25:40 EDT 2004


Em Mon, 5 Apr 2004 16:20:40 -0700 (PDT), Marilyn Davis
<marilyn at deliberate.com> atirou este peixe aos pinguins:

>> 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
>
>I think that attributes of Outer are not visible from Inner anyway?
>Do I have that right?
>

Well, if self is implicit, inside the Inner amethod only one self can
be visible. It seems logical that the it be the Inner self. But then,
because of impliciteness, you cannot get at the Outer self.

Now, let us try the same with the current rules.

class Outer(object)
    def amethod(outerself, arg):
        outerself.arg = arg
        class Inner(object):
            def amethot(self, arg):
                self.arg = arg*(outerself.arg)
            return Inner(1)

See the difference? Because of explicit naming, in the Inner amethod,
outerself is visible (because of nested scopes).

Of course, you can still get around this in the implicit case by
renaming, but IMHO, added to the other reasons, I think implicit self
is bad.

With my best regards,
G. Rodrigues



More information about the Tutor mailing list