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

Kent Johnson kent37 at tds.net
Wed Sep 7 05:24:12 CEST 2005

John Burk wrote:
> 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.
> I've tried something like this:
> <asset.py>
> class Asset: pass
> <foo.py>
> class Foo(Asset): pass
> <script.py>
> from asset import Asset
> from foo import Foo
> klass = 'Foo'
> o = klass()
> which gets me 'string not callable', which is kind of expected.

  klass = globals()['Foo']
  o = klass()

Alternately you could import all the Asset classes into a module with

from asset import Asset
from foo import Foo

then in your main script use
import assets
klass = getattr(assets, 'Foo')
o = klass()

Then the main script doesn't need to know any of the details of which asset types are defined.


More information about the Tutor mailing list