The need to put "self" in every method
Ron Adam
rrr at ronadam.com
Fri Jun 3 18:36:14 EDT 2005
Fernando M. wrote:
> Hi,
>
> i was just wondering about the need to put "self" as the first
> parameter in every method a class has because, if it's always needed,
> why the obligation to write it? couldn't it be implicit?
>
> Or is it a special reason for this being this way?
>
> Thanks.
Here's how I view it... (It may not be strictly correct, so corrections
are welcome.)
It helps to think of new style class's as code patterns or templates to
create class-instance objects. Since you don't know what the name of
the instance object is going to be when you write the class, a way to
refer to the contents of the not yet created object is needed.
Passing the class-instance reference as the first argument is how Python
gets a reference to the local name space of the method. You can then
use that name to access the other objects in the class-instance or to
create new objects in the class-instance from within the method without
knowing what the class-instance name is before hand.
Python doesn't pass the 'self' reference when a locally defined function
is called inside a class or method. By having to *explicitly* receive
the 'self' reference in the argument list, it is clear when the 'self'
reference is available for use and when it's not.
Cheers,
_Ron_Adam
More information about the Python-list
mailing list