Home >Backend Development >Python Tutorial >Share examples of how to use strings to call functions and methods in Python
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 callableWe hope to traverse the execution list function, but the function name obtained from the list is a string, so a type error will be prompted, and the string object cannot be called. What if we want the string to become a callable object? Or do you want to call module attributes and class attributes through variables?
There are three ways to achieve this.
eval()
>>> for func in func_list: eval(func)() foo bareval() is usually used to execute a string expression and returns the value of the expression. Here it converts the string into the corresponding function. eval() is powerful but dangerous (eval is evil) and is not recommended.
locals() and globals()
>>> for func in func_list: locals()[func]() foo bar >>> for func in func_list: globals()[func]() foo barlocals() and globals() are two of python Built-in functions through which local and global variables can be accessed in a dictionary.
getattr()
>>> import foo >>> getattr(foo, 'bar')()Returns the properties of the Foo class
>>> 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!