[Tutor] why "self" in methods?

Marilyn Davis marilyn at deliberate.com
Tue Apr 6 13:13:01 EDT 2004


On Tue, 6 Apr 2004, Gonçalo Rodrigues wrote:

> 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?

No.  I didn't have that right!  And that was my confusion.

> >
> 
> 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).

Indeed.  I ran your code:

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

########################################
# bash-2.05a$ python2.2 -i outer.py
# >>> x = Outer
# >>> x = Outer()
# >>> y = x.amethod('hey')
# >>> y.amethod('ho')
# ho hey
# >>> 


> 
> 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.

Explicit is better for sure!

Thank you for your patience!

Marilyn

> 
> With my best regards,
> G. Rodrigues
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 




More information about the Tutor mailing list