23

好的,我知道您可以使用 dir() 方法列出模块中的所有内容,但是有没有办法仅查看该模块中定义的函数?例如,假设我的模块如下所示:

from datetime import date, datetime

def test():
    return "This is a real method"

即使我使用inspect() 过滤掉内置程序,我仍然会留下任何导入的内容。例如我会看到:

['日期','日期时间','测试']

有没有办法排除进口?或者另一种找出模块中定义的方法?

4

5 回答 5

30

你在寻找这样的东西吗?

import sys, inspect

def is_mod_function(mod, func):
    return inspect.isfunction(func) and inspect.getmodule(func) == mod

def list_functions(mod):
    return [func.__name__ for func in mod.__dict__.itervalues() 
            if is_mod_function(mod, func)]


print 'functions in current module:\n', list_functions(sys.modules[__name__])
print 'functions in inspect module:\n', list_functions(inspect)

编辑:将变量名称从“meth”更改为“func”以避免混淆(我们在这里处理的是函数,而不是方法)。

于 2009-07-10T00:36:47.820 回答
4

以下情况如何:

grep ^def my_module.py
于 2009-07-09T22:59:22.247 回答
2

您可以检查__module__相关功能的属性。我说“函数”是因为一个方法通常属于一个类;-)。

顺便说一句,一个类实际上也有__module__属性。

于 2009-07-09T23:47:26.317 回答
1

python中的每个类都有一个__module__属性。您可以使用它的值来执行过滤。看一下潜入python中的示例6.14

于 2009-07-09T22:53:53.257 回答
0

python检查模块可能是您在这里寻找的。

import inspect
if inspect.ismethod(methodInQuestion):
    pass # It's a method
于 2009-07-09T22:56:42.207 回答