[Tutor] Another try at Python's selfishness

Ed Singleton singletoned at gmail.com
Sat Feb 4 11:36:28 CET 2006


On 04/02/06, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > 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.

As always Alan, you've managed to make something confusing seem
sensible and logical.

That is the best explanation of this subject I've ever heard.

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

I now agree, and (I think) understand completely.

Ed

PS Are there any good tutorials on the more philosophical side of the
object orientedness of Python?  I've read pretty much all the major
tutorials that are commonly linked to, and they often cover HOW to use
classes and stuff, but I'm quite interested in WHY we use classes (and
as I've discovered from you and Kent, WHEN to use classes).   I've
found some general OOP tutorials, but they always seem to use Java or
C which I don't know and don't particularly care to know.


More information about the Tutor mailing list