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

John Fouhy john at fouhy.net
Wed Sep 7 03:45:58 CEST 2005


On 07/09/05, John Burk <jburk at radical.ca> wrote:
> 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.

Would it be practical to use a dict?  Something like:

class Foo(Asset):
 pass
class Bar(Asset):
 pass

assetDict = { 'Foo':Foo, 'Bar':Bar }

You could split it out into modules too:

### AssetDict.py ###
assetDict = {}
###

### Foo.py ###
from Asset import Asset
import AssetDict

class Foo(Asset):
 pass
AssetDict.assetDict['Foo'] = Foo
###

### script.py ###
import AssetDict

klass = 'Foo'
o = AssetDict.assetDict[klass]()
###

Where is the class type coming from? Is it not feasible for you to
just do everything in terms of class objects? (which can be imported,
passed around, etc. just as easily as strings can be)

--
John.


More information about the Tutor mailing list