Strings are a commonly used data type in python, and it is very necessary to master the common methods of strings. The following article mainly introduces you to the relevant information about calling functions or methods through strings in Python. Friends who need it can refer to it. Let’s take a look together.
Preface
This article mainly introduces to you the relevant content about calling functions or methods using strings in Python, and shares it for your reference and study , let’s take a look at the detailed introduction:
Let’s look at an example first:
##
>>> def foo(): print "foo" >>> def bar(): print "bar" >>> func_list = ["foo","bar"] >>> for func in func_list: func() TypeError: 'str' object is not callable
There are three ways to achieve this.
eval()
>>> for func in func_list: eval(func)() foo bar
locals() and globals()
>>> for func in func_list: locals()[func]() foo bar >>> for func in func_list: globals()[func]() foo bar
getattr()
>>> import foo >>> getattr(foo, 'bar')()
>>> class Foo: def do_foo(self): ... def do_bar(self): ... >>> f = getattr(foo_instance, 'do_' + opname) >>> f()
Summarize
The above is the detailed content of Share examples of how to use strings to call functions and methods in Python. For more information, please follow other related articles on the PHP Chinese website!