[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 
names?
The dictionary could be a class attribute of the top level superclass or a 
module
level dictionary. It should be updated ideally by the class definition or 
more
simply by hard coding a registration fuinction.

Something like

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

class Sub(Root):
    pass
Root.registerSubclass("Sub",Sub)

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.

HTH

Alan G. 



More information about the Tutor mailing list