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.
Try klass = globals()['Foo'] o = klass() Alternately you could import all the Asset classes into a module with <assets.py> from asset import Asset from foo import Foo etc 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. Kent _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
