【问题标题】:How do I check in Python if a function belongs to a module如果函数属于模块,我如何检查 Python
【发布时间】:2017-07-27 10:04:08
【问题描述】:

我有一个已加载的模块,我检查了它的所有功能以检查它们是否具有特定参数。如果有,我会运行这些函数;

问题是模块也会有它自己的导入,它会添加到函数列表中,并且导入模块的一些函数也会运行。我需要检查一个函数是否属于某个模块。

import bar;
def function(special_param):
    #dostuff

bar 中,我有一个名为other_functionspecial_param 的函数。通过导入它,Python 会导入它的所有函数。如何检查other_function 是否属于bar

【问题讨论】:

标签: python function module


【解决方案1】:
if hasattr(bar, 'other_function'):
    do_something()

注意other_function 也可能是bar 中的变量,而不是函数。

编辑:这是Determine if a function is available in a Python module 的副本,其中@macrog 给出了更好的答案。改用它。 (将您的问题标记为重复)

【讨论】:

    【解决方案2】:

    你可以试试这个,

    if hasattr(bar, 'other_function'):
            getattr(bar, 'other_function')('Special_parameter')
    

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2012-03-23
      • 2016-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多