"self" - a python wart or "feature"

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Feb 17 08:49:16 EST 2003


"John Roth" <johnroth at ameritech.net> wrote in 
news:v51m6ufe8pkk15 at news.supernews.com:

> To give you an example of the issues with local variables,
> look at the "global" statement. It's there specifically to
> insure that you can assign to a variable at module level (that is,
> outside of the function definition.) If you didn't have an explicit
> "self," you'd have to do the same thing for classes.

I wouldn't want to lose the explicit self in the argument list (there are 
just too many good reasons why it is to be preferred), but there could be 
an argument for adding a "global" equivalent to make self optional when 
referring to instance variables:

   def aMethod(self, x):
       instance p, q, r
       p = q * x + r # Equivalent to: self.p = self.q * x + self.r

The benefit would be improved readability in expressions with a lot of 
instance variables.

(The word 'self' isn't intended to be special here, instance would simply 
mean the specified names are attributes of the first parameter. Assigning 
to the first parameter in a method using instance would be either illegal 
or undefined.)

One might then consider a 'local' keyword whose use would mean that all 
local variables in the current scope must be listed in one of 'global', 
'instance' or 'local'. Any other names would cause an error at compile 
time.

Of course it might be better simply to get unittest to generate warnings if 
there are any classes/functions/methods not exercised by tests. :-)

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list