understanding self

David Fraser davidf at sjsoft.com
Thu Jul 8 03:02:11 EDT 2004


Jeff Shannon wrote:
> 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.

You are assuming here that "self." would be implied on potential 
attribute accesses (like this in C++). The reason this is problematic is 
that it complicates Python's scoping structured. But it is not 
neccessarily the only way that having an implicit self could be used - 
self could be implicit in the parameter list, but explicit for any other 
use.

For example, there could be a keyword 'method' which defines a method 
object that takes self as its first parameter even though it's not 
declared. So the two __cmp__ definitions below would be equivalent:

class Complex:
     # ...
     def cmpabs(self, other):
         return self.abs().__cmp__(other.abs())
     method cmpabs2(other):
         return self.abs().__cmp__(other.abs())

a = Complex(3,4)
b = Complex(4,3)
print a.cmpabs(b)
print a.cmpabs2(b)

David



More information about the Python-list mailing list