tags:

views:

92

answers:

2

Say I have a class object named test.

test has various methods, one of them is whatever() .

I have a variable named method = "whatever"

How can I access the method using the variable with test?

Thanks!

+6  A: 

Get the attribute with getattr:

method = "whatever"
getattr(test, method)

You can also call it:

getattr(test, method)()
Ned Batchelder
+2  A: 

To access the method, getattr(test, test.method); this way you can bind it to a variable, return it as a function result, pass it as an argument, and so forth. To call it as well, append parenthesized arguments (just parentheses if there are no arguments), for example getattr(test, test.method)().

Alex Martelli