[Tutor] how to create a generic instance of an object?

John Burk jburk at radical.ca
Wed Sep 7 03:23:54 CEST 2005

I've got a base class "Asset", and currently have about 20 sub-classes
(assetTypes) that will inherit from it, with more to follow, I'm sure.
All of the assetTypes will have the same methods, but they'll be
polymorphic; each assetType's methodA() will do something slightly
different from it's sibling assetTypes.

What I want to do is to pass in the assetType at runTime via an external
script, create a new instance of it, and then run that instance's
methods.  That way I won't have to have 20 or more " if assetType== "
if/elif statements, and maintaining the script that creates new
instances won't become a nightmare.

And changing the base class' __init__ to contain another if/elif every
time someone adds another assetType seems to be so wrong, I rejected
that approach out of hand.  I want to design this thing so that the base
class doesn't need to know about all the sub-classes.

Perhaps I'm taking the wrong approach here with the Asset/AssetType
base-class/sub-class organization; it's beginning to feel that way.

I've tried something like this:

class Asset: pass

class Foo(Asset): pass

from asset import Asset
from foo import Foo

klass = 'Foo'
o = klass()

which gets me 'string not callable', which is kind of expected.

On p.325 of the O'Reilly Learning Python (2nd ed.), there's an example
of generic instance creation, but the values passed in are class
objects, not strings...  I'm guessing that this works because it's all
in the same module, so it knows that the things in the tuple iterated
over in the foreach are classes.

Any ideas?  I'm an old hand at perl (10+ years), but very new to Python,
so please be patient.

John Burk

More information about the Tutor mailing list