[Tutor] how to create a generic instance of an object?
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Wed Sep 7 03:54:58 CEST 2005
> 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:
>
> <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.
Hi John,
It sounds like you're trying to do some kind of dynamic linking. Python
has a builtin called "__import__" that can help: it allows us to do module
import, given an arbitrary name.
Your example above might be written as:
#####################################################################
<asset.py>
class Asset: pass
<foo.py>
class Foo(Asset): pass
<script.py>
def dynamic_lookup(module_name, class_name):
module_object = __import__(module_name)
class_object = getattr(module_object, class_name)
return class_object
klass = dynamic_lookup('foo', 'Foo')
o = klass()
#####################################################################
This can be easily abused. *grin* But for what you're trying, it might be
what you're looking for. For more information on __import__, see:
http://www.python.org/doc/lib/built-in-funcs.html
Hope this helps!
More information about the Tutor
mailing list