Scope and classes

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Aug 19 11:31:55 CEST 2009

David a écrit :

> Out of 'Abc.message' and 'self.message', which is the favoured
> convention? It would be very easy to accidentally override
> 'self.messages' with an instance attribute!

Only use 'Abc.message' if you want to make sure you get the Abc class 
'message' attribute - that is, if you want to skip possible overrides in 
subclasses. As far as I'm concerned, I'd tend to consider this bad style 
  unless it's a very very specific implementation point of an abstract 
class (in which case it would probably be named '__message' to prevent 
accidental override) - but YMMV of course.

Use 'self.__class__.message' (or 'type(self).message') if you want to 
make sure you get the class 'message' attribute - that is, if you want 
to honor possible overrides in subclasses, but not per-instance 
override. But then - at least in your example code - I'd use a classmethod:

class Abc:
     message = 'Hello World'

     def print_message(cls):
         print cls.message

Now the most common idiom - that is, outside classmethods - is to just 
use 'self.message'. Someone (even you) might have a very valid reason to 
  override the 'message' attribute on a per-instance basis. FWIW, if you 
start to worry about possible accidental overrides here, then Python 
might not be the right language for you - nothing prevents "accidental" 
overrides of method and even the class (the '__class__' attribute) 
itself - yes, they are all attributes, and you can dynamically override 
them !-)

More information about the Python-list mailing list