understanding self

Jeff Shannon jeff at ccvcorp.com
Thu Jul 8 14:03:56 EDT 2004


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




More information about the Python-list mailing list