开发者

How do I access a object's method when the method's name is in a variable?

Say I have a class object named test.

test has various methods开发者_如何学JAVA, one of them is whatever() .

I have a variable named method = "whatever"

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

Thanks!


Get the attribute with getattr:

method = "whatever"
getattr(test, method)

You can also call it:

getattr(test, method)()


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜