understanding self

Jeff Shannon jeff at ccvcorp.com
Thu Jul 8 02:09:33 CEST 2004


bruce stockwell wrote:

>Using 'self' in classes seems pretty straight forward. My curiosity is 
>why I have to use it. Shouldn't it be implied? 
>

The problem is that an implied 'self' is harder to read than an explicit 
'self', and also opens the door for ambiguity when an instance attribute 
has the same name as a global or builtin attribute.

Let's look at an example in a hypothetical Python variant where 'self' 
is implied --

class eye:
    def open(which):
        # do stuff here

    def close(which):
        # do stuff here

    def blink(which):
        if closed:
            open(which)
            close(which)
        else:
            close(which)
            open(which)

e = eye()
e.blink('right')

But wait -- open() is an obsolete built-in function for opening a file.  
Which should eye.blink() do -- open and close the right eye, or open a 
file with the name of 'right' ??  If it's the former, then what do you 
do if you *want* to open that file?  If it's the latter, then what 
happens when the next version of Python comes along and open() has been 
removed from built-ins?

Even without these namespace conflicts, it's difficult when you're 
reading a long method and see a call to "make_thingumbob()" -- where do 
you look to see what that does?  It might be another method of that 
class, or it might be a global (or even built-in) function.  It then 
requires extra thought and search-time to figure out the intent.

One of the design principles of Python is that ease of *reading* is more 
important than ease of *writing*.  It's worth a few extra keystrokes if 
it will save you a second or two of time when reading unfamiliar code -- 
because most code is only written once, but read *many* times.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list