[Tutor] Scope and elegance revisited
Kent Johnson
kent37 at tds.net
Wed Jan 9 21:37:58 CET 2008
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.).
> def main():
> Foo.class_variable = "Done"
> Foo()
>
>
> if __name__ == '__main__': main()
>
>
> Running the script prints out "Done" as expected.
>
> However, this looks ugly to me. Is there a more elegant way of doing
> this?
Seems OK to me.
> To give you the context: my application allows you to select a skin for
> the user interface. I want to set the access path to the skin folder as
> a class variable, so that all instances of that class use images from
> the appropriate folder. The access path will be read in from a
> preferences file before any instances of the class are created.
Why do you have multiple instances of the class? You might be interested
in the Borg pattern:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
Kent
More information about the Tutor
mailing list