On Mon, Feb 15, 2010 at 10:29 AM, Leo Breebaart <l...@lspace.org> wrote: > 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.
Metaclasses to the rescue!: class WithTemplateAttrs(type): def __new__(cls, name, bases, dct): klass = type.__new__(cls, name, bases, dct) klass.template_filename = "%s.tmpl" % name klass.template_body = read_body_from(klass.template_filename) return klass class Foo(object): __metaclass__ = WithTemplateAttrs #rest of class body here Now just have FooA, FooB, etc. subclass Foo as before. They'll automatically get the attributes generated. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list