我是 Python 的新手,遇到这样的情况,我有一个代表模块内部函数的变量,我想知道如何动态调用它。我有 filters.py
:
def scale(image, width, height):
pass
然后在另一个脚本中我有类似的东西:
import filters
def process_images(method='scale', options):
filters[method](**options)
...但这显然行不通。如果有人可以告诉我执行此操作的正确方法,或者让我知道是否有更好的方法将函数作为参数传递,那就太棒了。
最佳答案
你需要内置 getattr
:
getattr(filters, method)(**options)
关于Python - 动态调用模块中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3190583/