Home >Backend Development >Python Tutorial >Share examples of how to use strings to call functions and methods in Python

Share examples of how to use strings to call functions and methods in Python

黄舟
黄舟Original
2017-08-04 10:42:161743browse

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

We 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
bar

eval() 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
bar

locals() and globals() are two of python Built-in functions through which local and global variables can be accessed in a dictionary.

getattr()

getattr() is a built-in function of Python, getattr(object,name) is equivalent to object.name, but here name Can be a variable.

Returns the bar method of the foo module


>>> 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Python learning rulesNext article:Python learning rules