Instantiate arbitrary classes at run time

Robert Cragie rcc at jennic.com
Fri Mar 31 03:28:17 EST 2000


<jiml at longson.com> wrote in message news:8c052p$beg$1 at nnrp1.deja.com...
> In article <CC59868A0A76D311B1F50090277B321C1F322D at VRTMAIL>,
> Mike Fletcher <mfletch at tpresence.com> wrote:
> > Here's a simple little function that does the basic work...
> >
> ...trimmed....
> Thanks for the suggestion. Very impressed with responses from this
> group. I turned your suggestion into a simple class which may be
> helpful to others.
> title = 'Arbitrary Class'
> import string
> import sys
> class ArbitraryClass:
> def getClass(self, moduleName):
> return __import__(
> moduleName,
> {},
> {},
> []
> )
> def getInstance( self, moduleName ):
> return getattr( self.getClass( moduleName ), moduleName)()
> ######################################################################
> # Run from command line
> if __name__ == '__main__':
> arbitrary = ArbitraryClass()
> #select any arbitrary class name
> target = "any_class"
> #create an instance of any_class
> instance = arbitrary.getInstance( target )
> print instance.any_method() #call any_method in any_class
> sys.exit()
>

Good solution - I'm learning all the time. A couple of points:

1) The class must be defined in a module of the name name.
2) It doesn't handle constructor arguments as is. This can be done like so:

######### in module MyClass.py #########
class MyClass:
    def __init__(self, data):
        print data
####################################

class ArbitraryClass:
    def getClass(self, cmName):
        return __import__(cmName, {}, {}, [])

    def getInstance(self, cmName, *args, **kwargs):
        return apply (getattr(self.getClass(cmName), cmName), args, kwargs)

if __name__ == '__main__':
    arbitrary = ArbitraryClass()
    target = 'MyClass'
    instance = arbitrary.getInstance(target, 'Hello world')

Robert Cragie






More information about the Python-list mailing list