Instantiate arbitrary classes at run time

jiml at longson.com jiml at longson.com
Thu Mar 30 13:06:32 EST 2000


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()


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list