【问题标题】:Fetching the function names from module in python从python中的模块中获取函数名
【发布时间】:2015-11-19 13:05:05
【问题描述】:

for doing -- from audit.status 导入状态 其中,audit.status 中的“status”是模块名,最后一个“status”是类名。

我使用__import__ 作为,

temp = __import__ ("audit.status"), globals=(), locals=(), fromlist=["status"]

classname = temp.status 

而且它工作得很好,但是我如何使用我在下面的语句中使用上述方法获取的模块名称来获取函数名称:

[obj for obj in getmembers(module_name) if isfunction(obj[1])]

【问题讨论】:

  • getmembersisfunction 定义在哪里?您是否有任何未向我们展示的import 声明?请向我们展示您未向我们展示的所有导入语句。
  • from inspect import getmembers, isfunction
  • 请编辑您的问题,而不是在评论中回答
  • 我没有在 cmets 中回答......我的问题很清楚......我只是在回复这些 ppls cooments
  • 顺便提一下,inspect.isfunction 对于内置函数和类方法都返回 False。这在文档中并不完全明显。

标签: python file python-2.7 operating-system


【解决方案1】:

如果你问“我怎样才能找到模块对象的所有可调用属性?”,

>>> import math
>>> attrs = [getattr(math, name) for name in dir(math)]
>>> callables = [attr for attr in attrs if hasattr(attr, "__call__")]
>>> print callables
[<built-in function acos>, <built-in function acosh>, <built-in function asin>,
...
<built-in function tan>, <built-in function tanh>, <built-in function trunc>]

或者,如果您只想要名称而不是属性本身,

>>> names = [name for name in dir(math) if hasattr(getattr(math, name), "__call__")]
>>> print names
['acos', 'acosh', 'asin', ... 'tan', 'tanh', 'trunc']

【讨论】:

  • 在将模块名称传递给 getmembers() 时我做错了什么......因为它给了我空的函数列表。
  • 我不知道getmembers是什么,但你不需要使用它。我的回答在任何地方都不需要getmembers
  • 我试过了,[method for method in dir(classname) if callable(getattr(cname,method))] 但这给了我所有属性的列表,例如“class", "format" 以及类本身的方法以及父类的方法和属性...有没有办法我可以过滤掉它以仅获取类名 i 的方法我提供
  • 确保您提供的是模块对象而不是模块名称,无论您在哪里用模块替换“数学”。否则,您将只检查 string 类。
猜你喜欢
  • 2013-09-13
  • 2010-11-08
  • 1970-01-01
  • 1970-01-01
  • 2014-12-14
  • 2017-02-27
  • 2017-11-23
  • 1970-01-01
  • 2013-11-06
相关资源
最近更新 更多