[Tutor] Scope and elegance revisited
Michael H. Goldwasser
goldwamh at slu.edu
Thu Jan 10 04:09:50 CET 2008
On Wednesday January 9, 2008, Kent Johnson wrote:
> James Newton wrote:
> > Hi Python Purists!
> > I want all instances of a given class to share a piece of information,
> > but I want to set that information on the fly. I have found that this
> > works:
> > class Foo(object):
> > # class_variable = None # There is no real need to declare this
> > def __init__(self):
> > print self.__class__.class_variable
> could be just self.class_variable, attributes are looked up in the class
> if not found in the instance (that's how method access works, e.g.).
Though Kent is correct that the class namespace will be searched when
the variable is not found in the instance namespace, I still prefer to
use the syntax Foo.class_variable in this context as it makes the
code more legible in regard to this being a class variable.
The only reason I can imagine using the self.__class__ syntax would be
if you expect subclasses to be defined and intentionally want to rely
on the subclass namespace rather than Foo.
> > def main():
> > Foo.class_variable = "Done"
> > Foo()
Notice the above change matches the style you are using in main().
More information about the Tutor