How to call a class method from a string representing a class name

Andre Fortin andrefor at axionet.com
Sun Jan 28 13:05:18 EST 2001


Hi!,


I'm trying to do the following: if there is an object named 'test' in
this namespace,
call its well-known class method 'myFunc'. The 2 snippets of code below
show how I'm currently doing this. 

Is there a better/easier way, avoiding globals() and vars() ?

Thanks,

-- Andre


#------------ Main file: question.py -------------------
#! /usr/bin/env python


import test

className = 'test'

try:
    myObj = globals()[className]
    apply(vars(myObj)['myFunc'], ('Some text',))
except KeyError:
    pass


#------------ File 2: test.py -------------------
class test:
    pass

def myFunc(someText):
    print "[%s]" % someText



More information about the Python-list mailing list