[Tutor] why "self" in methods?
Alan Gauld
alan.gauld at blueyonder.co.uk
Tue Apr 6 13:28:11 EDT 2004
>> class Outer(object):
>> def amethod(arg):
>> class Inner(object):
>> def amethod(arg):
>> self.arg = arg #What's self here?
>> return inner()
>>
>
>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.
The C++ approach to this would be to use the scoping operator '::'
so you could access the data, within the scoping rules, using
Outer::amethod(). Although in C++ nested classes are discouraged
and friends preferred:
class Inner{
friend class Outer;
private: int foo;
...};
class Outer{
Inner myInner;
int& bar = myInner.foo; // direct access to inner members here
...};
Which is all pretty messy and shows why explicit self is better!
> 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?
Neat! Although I still haven't thought of a need to do that,
but its nice to know you can! :-)
Alan G.
More information about the Tutor
mailing list