Using class attributes
Leo Breebaart
leo at lspace.org
Mon Feb 15 13:29:38 EST 2010
I have a base class Foo with a number of derived classes FooA,
FooB, FooC, etc. Each of these derived classes needs to read
(upon initialisation) text from an associated template file
FooA.tmpl, FooB.tmpl, FooC.tmpl, etc.
I can derive the template filename string for each instance by
doing something like this in the base class (and then not
forgetting to call super() in the __init__() of each derived
class):
class Foo(object):
def __init__(self):
self.template_filename = "%s.tmpl" % self.__class__.__name__
self.template_body = read_body_from(self.template_filename)
But, since this information is the same for every instance of
each derived class, I was wondering if there was a way to achieve
the same thing outside of the __init__ function, and just have
these assignments be done as a class attribute (i.e. so that I
can refer to FooA.template_body, etc.)
I can of course always just hardcode the template filenames in
each derived class, but I am just curious if it can be automated
through some form of introspection.
--
Leo Breebaart <leo at lspace.org>
More information about the Python-list
mailing list