[Tutor] Another try at Python's selfishness
Alan Gauld
alan.gauld at freenet.co.uk
Sat Feb 4 01:24:14 CET 2006
> I have to say that as a newbie, it took me quite a while to get my
> head around that extra parameter (self).
That's OK, its true of most folks, even non newbies!
It is one area where Python is different to most languages
who hide the self completely.
> It took me ages to work out that:
>
>class A:
> def __init__(self, foo):
> self.foo = foo
>
> a = A("hello")
>
> is actually a shortcut for:
>
> a = A(a, "Hello")
> I think insisting on:
>
> a = A(a, "Hello")
>
> would be very good for readability, understandability and
> newbie-friendliness.
Only for the constructor.
Once you have the object itself the method calls wouyld be much less
readable:
class C:
def a(s):pass
c = C()
c = c.a(c)
etc
is not descriptive of the concept of passing a message to the object c,
it looks rather like you are passing the object c to a function which is
a member of itself, which brings to mind recursion not messages...
Remember that the purpose of writing a class is to *hide* the details of
its implementation from the user, thus the user never has to use self,
only the builder. The only reason you are confused is because you
are both builder and user of the class.
But consider file objects, do you ever feel the need to write:
myfile = file(myfile,filename,mode)
or does
myfile = file(filename,mode)
seem more friendly? Is that because you've nbever actually
seen the constructor code for the file class(*) and so don't
worry about the presence of self?
If you did have to pass the object in, wouldn't you be asking
why you had to pass the object into the file creation method?
(*)OK I haven't checked, but I strongly suspect the built in
file objects aren't written in Python so won't look the same
but the illustration is valid.
I dunno if that helps explain the rational but maybe...
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list