python - 动态调用函数 - Python

标签 python

我有一个函数列表...例如

def filter_bunnies(pets): ...

def filter_turtles(pets): ...

def filter_narwhals(pets): ...

有没有办法通过使用代表函数名称的字符串来调用这些函数?

例如

'filter_bunnies', 'filter_turtles', 'filter_narwhals'

最佳答案

您的函数是对象的一部分吗?如果是这样,您可以使用 getattr功能:

>> class A:
    def filter_bunnies(self, pets):
        print('bunnies')

>>> getattr(A(), 'filter_bunnies')(1)
bunnies

关于python - 动态调用函数 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2818490/

相关文章:

python - 使用 Python 代码按日期提取数据并另存为单独的 csv Datewise

python - Twine 无法识别 --repository-url 标志

python - 使用 Python 重命名目录

python - 如果图像具有形状(28,28,3,1),我如何将其转换为形状(28,28,3)?

Python 3.6 属性错误 : module 'statsmodels' has no attribute 'compat'

python - 无法 apt-get 安装包 E : Sub-process/usr/bin/dpkg returned an error code (1)

python - Pandas :根据多级首次出现合并数据框

python - Tkinter(python) 禁用按钮调用方法

python - 如何使用 python 将 web3 连接到主以太坊网络?

Python 获取特定角色的所有成员列表