How to instatiate a class of which the name is only known at runtime?

kosh kosh at aesaeion.com
Wed Sep 10 04:15:38 EDT 2003


On Wednesday 10 September 2003 01:12 am, Max M wrote:
> Max M wrote:
> > import class1, class2, class3
> >
> > def Factory(class_type):
> >     if class_type='class1':
> >         return class1()
> >     elif class_type='class2':
> >         return class2()
> >     elif class_type='class2':
> >         return class3()
> >

use

def Factory(class_type):
  factory = {
    'class1':class1,
    'class2':class2,
    'class3':class3}
  try:
    return factory[class_type]()
  except KeyError:
    pass 

That will expand nicely and only needs a single lookup. Change the except 
condition to match what you what you want to happen when the class is not 
found. I have one factory that can make one of about 50 objects and doing an 
if elif structure would suck for that. Also if you want create that data 
structure outside that method so that you only create it once although that 
is not really an issue since it works very fast.

> >
> >
> > # using the factory
> > from Factory import Factory
> > myObject = Factory(class2)
>
> That last line should read:
>
> myObject = Factory('class2')
>
> Max M





More information about the Python-list mailing list