[Tutor] how to create a generic instance of an object?
John Burk
jburk at radical.ca
Wed Sep 7 22:02:16 CEST 2005
-----Original Message-----
From: Danny Yoo [mailto:dyoo at hkn.eecs.berkeley.edu]
Sent: Tuesday, September 06, 2005 6:55 PM
To: John Burk
Cc: tutor at python.org
Subject: Re: [Tutor] how to create a generic instance of an object?
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!
And the winner is Danny Yoo, for the cleanest implementation. Some of
my design goals for this class heirarchy were:
* end-users of the class heirarchy should be able to add new sub-classes
without modifying any of the other base or sub-classes.
* an exhaustive list of all sub-classes should be unneccesary
* likewise, any front-end script that uses this class shouldn't have a
long list of 'import' statements.
Danny's method helped me meet all these goals.
The approach outlined above models the 'import <module>' behavior. I'm
using a namespace to differentiate all our home-grown classes and
modules, and because I'm trying to model the 'from rad.<class> import
<Class>, my implementation looks like:
=============================================================
def dynamic_lookup(module_name, class_name):
module_object = __import__(module_name, globals(), locals(),
[class_name])
class_object = getattr(module_object, class_name)
return class_object
aType = 'foo'
aName = 'bar'
klass = dynamic_lookup( 'rad.' + aType, aType.capitalize() )
o = klass(aName)
=============================================================
Thanks to all who replied.
johnb
More information about the Tutor
mailing list