Why self?

Andrew Koenig ark at research.att.com
Tue Jul 9 09:00:36 EDT 2002


Louis> Ugly is in the eye of the beholder.  I think it's cleaner (a design
Louis> goal of Python as I recall).

I'm not convinced.

I see two problems:

1) In Python, it is generally not possible to determine what the
   attributes of an object are by statically examining the source.
   For example:

        class Thing:
                def __init__(self):
                        setname(self)

                def printname(self):
                        print self.name

        def setname(x):
                x.name = "Thing"

At the time the compiler encounters the "print self.name" statement,
how would it know that name is an attribute of the object of which
printname is a member?  Note that it hasn't seen the definition of
setname yet.

2) Methods are just functions that happen to be attributes.
In other words, we could have written this:

        class Thing:
                def __init__(self):
                        setname(self)

        def setname(x):
                x.name = "Thing"

        def printname(self):
                print self.name

        Thing.printname = printname

        t = Thing()
        t.printname()

effectively transforming printname into a method, even though it
does not have the form of a method when it is written.

It seems to me that dropping the explicit "self" would make these
two programs much messier.  In what way then is it cleaner?


(Incidentally, the analogous arguments do not apply to C++
because C++ requires that all of the members of a class be
known during compilation--with one exception, namely members
inherited from a template base class.  In that case, C++
requires the equivalent of an explicit "self" for essentially
the same reason.)

-- 
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark



More information about the Python-list mailing list