Python uses strings to call the function or method sample code, and python sample code
Preface
This article describes how to use strings to call functions or methods in Python. For more information, see the following:
Let's take a look at an example:
>>> def foo(): print "foo">>> def bar(): print "bar">>> func_list = ["foo","bar"]>>> for func in func_list: func()TypeError: 'str' object is not callable
We want to traverse the functions in the execution list, but the function name obtained from the list is a string, so a type error is 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 the attributes of the module and the attributes of the class through variables?
The following three methods can be implemented.
Eval ()
>>> for func in func_list: eval(func)()foobar
Eval () is usually used to execute a string expression and return the value of the expression. Here it converts the string to the corresponding function. Eval () is powerful but dangerous. It is not recommended.
Locals () and globals ()
>>> for func in func_list: locals()[func]()foobar>>> for func in func_list: globals()[func]()foobar
Locals () and globals () are two built-in functions of python. They allow you to access local and global variables in a dictionary.
Getattr ()
Getattr () is a python built-in function. getattr (object, name) is equivalent to object. name, But here name can be a variable.
Return the bar method of the foo module.
>>> import foo>>> getattr(foo, 'bar')()
Returns the property of the Foo class.
>>> class Foo: def do_foo(self): ... def do_bar(self): ...>>> f = getattr(foo_instance, 'do_' + opname)>>> f()
Summary
The above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, please leave a message, thank you for your support.
Reference
Calling a function of a module from a string with the function's name in Python
How do I use strings to call functions/methods?