Invoking a method by name?
Magnus Therning
magnus.therning at wanadoo.nl
Mon May 19 02:07:38 EDT 2003
I need to call a method of an object where I only have the name of the
method in a string. I have found one way, but I am not sure, maybe there
is a more beautiful way to accomplish it?
This is some example code:
import inspect
class test1:
def test(self):
print 'test'
class test2(test1):
def test(self):
print 'extended test'
def isrightfunc(name):
return lambda(x): inspect.ismethod(x) and x.__name__ == name
a = test1()
b = test2()
inspect.getmembers(a, isrightfunc('test'))[0][1]()
inspect.getmembers(b, isrightfunc('test'))[0][1]()
Of course the output is the expected one:
test
extended test
Thankful for all pointers.
/M
--
Magnus Therning (OpenPGP: 0x6A83A7DF)
First we thought the PC was a calculator. Then we found out how to turn
numbers into letters with ASCII, and we thought it was a typewriter. Then
we discovered graphics, and we thought it was a television. With the World
Wide Web, we've realized it's a brochure.
-- Douglas Adams
More information about the Python-list
mailing list