[Tutor] Dynamic inheritance?
kent37 at tds.net
Sun Nov 20 13:30:28 CET 2005
Jan Eden wrote:
> The situation is this:
> For every object, two string attributes are determined during
> initialization (one being read from a database, the other inherited
> as a superclass attribute). The first contains the site name, the
> second the object type. I'd like to set the template attribute to the
> proper class:
> import Templates
> self.site_name = 'SiteA'
> self.template_type = 'Page'
> self.template = ???
> self.template should refer to Templates.SiteA.Page in this case
> (where SiteA is a module of package Templates, and Page is a class
> within that module). Danny already said that classes can be treated
> just like any other object - but how do I get from a string to a
> class or module name?
Use getattr() to access attributes by name. SiteA is an attribute of Templates and Page is an attribute of SiteA so you can get use getattr() twice to get what you want:
site = getattr(Templates, self.site_name)
self.template = getattr(site, self.template_type)
> Thanks for all your help, and sorry for my ignorance,
No problem, this list is for beginners!
More information about the Tutor