import modules at runtime
Robert Cragie
rcc at nospamthanks_jennic.com
Wed May 10 07:33:16 EDT 2000
This was in a post dated 31/03/00. This works fine for a class which has the
same name as the module.
######### in module MyClass.py #########
class MyClass:
def __init__(self, data):
print data
####################################
class ArbitraryClass:
def getClass(self, cmName):
return __import__(cmName, {}, {}, [])
def newInstance(self, cmName, *args, **kwargs):
return apply (getattr(self.getClass(cmName), cmName), args, kwargs)
if __name__ == '__main__':
arbitrary = ArbitraryClass()
target = 'MyClass'
arg1 = 'Hello world'
instance = arbitrary.newInstance(target, arg1)
<martin_valiente at my-deja.com> wrote in message
news:8f6jd5$7mg$1 at nnrp1.deja.com...
| Hi *
|
| Is there a way to create an object instance giving its classname at
| runtime?
|
| In java you can say:
|
| ...
| Class c = Class.forName(stringWithTheNameOfTheClass);
| Object o = c.newInstance():
| ...
|
| Thanks in advance
| M.
|
|
| Sent via Deja.com http://www.deja.com/
| Before you buy.
More information about the Python-list
mailing list