use of "self", was "No Do while/repeat until looping construct in python?"

Chermside, Michael mchermside at ingdirect.com
Fri Mar 14 19:20:53 CET 2003


> On the other hand, if you have a valid reason why "self" is advantageous
> FROM THE USER's POINT OF VIEW I would like to hear it.

I'm not sure I really believe you (about desiring to hear a reason
why "self" is advantageous), but I'll give it a shot anyhow.

Consider the following Java snippet (sorry, I don't know Ruby well
enough to get the syntax right).

    public class MyClass extends ParentClass {
        String accessId;
        public MyClass(accessId) {
            this.accessId = accessId;
        }
        public int overlyLongFunction() {
            // Here goes 162 lines of messy code
            return (jiggerPercent > 100) ? 100 : jiggerPercent;
        }
    }

In the last line of overlyLongFunction, we refer to the
variable "jiggerPercent". This could be either a local
variable OR an instance variabler... and there's no way to
tell which one it is. Notice how the constructor uses a
common java idiom which makes use of this ambiguity.

In Python, it would refer to either "jiggerPercent" or
to "self.jiggerPercent", and the reader would be immediately
aware of which was intended. (Note that Python values 
terseness for the sake of the READER of the code, not because
the WRITER of the code has lazy fingers.)

Of course, Python isn't perfect in this regard... it still
has three different namespaces (local, global, built-in) where
the variable might live, but at least it distinguishes the
instance-variable namespace.

You can argue over whether you LIKE this feature, but it IS
a commonly-mentioned advantage of the use of self. Now you
said that "common sense says the instance variables are local",
but I believe this is a very odd use of the term of "common 
sense", given that instance variables are _NOT_ the same as
local variables... not in Python, in Java, or in Ruby. Doesn't
mean you have to like typing "self", but it IS one good reason
(among others) for requiring it.

-- Michael Chermside

PS: Problem for the readers: name another advantage of using 
self BESIDES distinguishing local and instance scopes. Extra 
credit if you come up with one I haven't heard before.





More information about the Python-list mailing list