Why self?

Jonathan Hogg jonathan at onegoodidea.com
Tue Jul 9 05:57:23 EDT 2002


On 8/7/2002 22:42, in article 3D2A06F9.7050805 at onsitetech.com, "Robb
Shecter" <rs at onsitetech.com> wrote:

> Good ideas.  Or just do nothing: make self optional as in Java, and the
> innermost scope is searched first if no self is given.  I've done
> years of Java programming, and have never had issues with instance vs.
> local variables.  It just really doesn't happen in practice because of
> the differences in naming and usage of variables.

Actually, one of my number one errors in Java was always stupid copy and
paste errors along the line of (not compiled, don't bother pointing out any
syntax errors):

    public void setX( int x )
    {
        this.x = x;
    }

    public void setY( int x )
    {
        this.y = y;
    }

which elicits no error but is completely wrong. Hint if you can't see it:
forgetting to change the name of the argument to the setY function - a 'y'
is in scope because 'this' is implicitly searched so there is no compile
error.

Because of this it's a standard practice in Java to write:

    public void setY( int inY )
    {
        this.y = inY;
    }

or something similar to avoid the confusion. I hate this with a passion. The
comparable function in Python would be:

    def setY( self, x ):
        self.y = y

which would fail immediately (as long as 'y' isn't a global variable - but
don't get me started on global variables...).

Explicitly writing 'self.' means that the difference between referencing a
local variable (or argument) and an instance variable is always obvious. I
have never had a bug in a Python program from confusing the two.

[Actually when writing Java programs I always explicitly reference 'this'
anyway because I want to be able to look at a line of code and know what's
what without having to look at the instance and local variable
declarations.]

-down-with-using-naming-conventions-to-differentiate-scopes-ly y'rs,

Jonathan




More information about the Python-list mailing list