[Tutor] Dynamic inheritance?

Alan Gauld alan.gauld at freenet.co.uk
Sun Nov 20 17:54:36 CET 2005

> import Templates
> self.site_name = 'SiteA'
> self.template_type = 'Page'
> self.template = ???

How about a dictionary holding references to the classes against their 
The dictionary could be a class attribute of the top level superclass or a 
level dictionary. It should be updated ideally by the class definition or 
simply by hard coding a registration fuinction.

Something like

class Root:
   subclasses = {'Root': Root}
   def registerSubclass(name, aClass):
        #could check it really is a subclass here...
        Root.subclasses[name] = aClass

class Sub(Root):

Now your code becomes:

 self.site_name = 'SiteA'
 self.template_type = 'Page'

 self.template = Root.subclasses[self.template_name]()  # instance of Page

In fact it could just be a dictionary of templates, it needn't be subclasses
at all, however for the sake of clean polymorphism its probably better
if they are.


Alan G. 

More information about the Tutor mailing list