Python: How Do You Call A Method When You Only Have The String Name Of The Method?
Solution 1:
For methods of instances, use getattr
>>>classMyClass(object):...defsayhello(self):...print"Hello World!"...>>>m=MyClass()>>>getattr(m,"sayhello")()
Hello World!
>>>
For functions you can look in the global dict
>>>defsayhello():...print"Hello World!"...>>>globals().get("sayhello")()
Hello World!
In this case, since there is no function called prove_riemann_hypothesis
the default function (sayhello
) is used
>>>globals().get("prove_riemann_hypothesis", sayhello)()
Hello World!
The problem with this approach is that you are sharing the namespace with whatever else is in there. You might want to guard against the json calling methods it is not supposed to. A good way to do this is to decorate your functions like this
>>>json_functions={}>>>defmake_available_to_json(f):... json_functions[f.__name__]=f...return f...>>>@make_available_to_json...defsayhello():...print"Hello World!"...>>>json_functions.get("sayhello")()
Hello World!
>>>json_functions["sayhello"]()
Hello World!
>>>json_functions.get("prove_riemann_hypothesis", sayhello)()
Hello World!
Solution 2:
The clean, safe way to do this is to make a dict mapping names to functions. If these are actually methods, the best way is still to make such a dict, though getattr
is also available. Using globals
or eval
is unsafe and dirty.
Solution 3:
Use getattr. For example:
classTest(object):
defsay_hello(self):
print'Hell no, world!!111'deftest(self):
getattr(self, 'say_hello')()
Solution 4:
Assuming the functions are all global variables (they are, unless they were defined inside another functions), they can be accessed with the globals()
function. globals()
returns a dictionary of all global variables, including functions.
For example:
$ python
Python 2.6.2 (r262:71600, Apr 162009, 09:17:39)
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type"help", "copyright", "credits"or"license"for more information.
>>> defsome_function():
... print"Hello World!"... >>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'some_function': <function some_function at 0x6326b0>, '__package__': None}
>>> globals()['some_function']()
Hello World!
Post a Comment for "Python: How Do You Call A Method When You Only Have The String Name Of The Method?"