Python - 动态调用模块中的函数

Chr*_*tte 10 python

我是Python的新手,我有一个情况,我有一个代表模块内部函数的变量,我想知道如何动态调用它.我有filters.py:

def scale(image, width, height):
    pass
Run Code Online (Sandbox Code Playgroud)

然后在另一个脚本中我有类似的东西:

import filters

def process_images(method='scale', options):
    filters[method](**options)
Run Code Online (Sandbox Code Playgroud)

......但这显然不起作用.如果有人能够以正确的方式填写我这样做,或者让我知道是否有更好的方法来传递函数作为参数,这将是非常棒的.

Sil*_*ost 16

你需要内置getattr:

getattr(filters, method)(**options)
Run Code Online (Sandbox Code Playgroud)


sth*_*sth 10

为避免此问题,您可以直接传递函数,而不是"按名称":

def process_images(method=filters.scale, options):
    method(**options)
Run Code Online (Sandbox Code Playgroud)

如果您有特殊原因要使用字符串,则可以getattr按照SilentGhost的建议使用.