understanding self

David Fraser davidf at sjsoft.com
Fri Jul 9 11:49:37 CEST 2004

Jeff Shannon wrote:
> David Fraser wrote:
>> 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())
> Another Python design principle is to minimize the number of keywords.  
> You *could* do that... but it doesn't really gain you anything except an 
> extra keyword.  And I personally find it clearer to see "self" in the 
> parameter list than to have to think "Oh yeah, this is a method, so 
> there's an implied self..."
> But most importantly, an implicit 'self' would violate the second "Zen 
> of Python" guideline -- "Explicit is better than implicit."  Unless you 
> can point to a significant *gain* by having 'self' implicit, then it's 
> better (or at least, more Pythonic) to have it explicit.  So far, I've 
> heard plenty of alternatives to having explicit 'self', but very little 
> indication of why it would be an improvement other than that it would 
> allow less typing -- and Python has always placed ease-of-reading over 
> ease-of-typing.  ("Readability counts.")
> (Heck, back when I was learning C++, I tended to explicitly use 'this' 
> when referring to class members/methods even though it was unnecessary, 
> simply because it made it easier to *see* what was a class member and 
> what wasn't; the "m_***" naming convention that's often used instead 
> strikes me as just being a weak way of doing the same thing...)
> Jeff Shannon
> Technician/Programmer
> Credit International

Actually the reason I think its worthwhile having another keyword here 
is that Python actually has separate types for functions and methods.
Explicit is better than implicit - at the moment the method binding to 
self all happens behind the scenes, and you have bound and unbound 
method types that are all produced using the 'def' keyword like 
functions, but can actually operate differently.

I think it is more readable, I'm not so concerned about the typing. 
There is magic happening here but no evidence for it ... a method 
keyword would justify the magic... That's why I still think you should 
refer to members of the class using self. rather than having magical 
name binding


More information about the Python-list mailing list