dir() 不会使用它的参数

dir() will not use its argument

我想在 Python 中编写一个小函数来打印对象的每个可调用方法。在 REPL 中,我会这样做以获得每个列表方法:

[x for x in dir([]) if '__' not in x]

这在 REPL 中工作正常,但是当我在模块中编写相同的理解时:

def methods(obj):
    return [x for x in dir(obj) if '__' not in x]

我收到一个错误: "TypeError: dir() takes no arguments (1 given)." 问题出在哪里?为什么将它写在 REPL 中而不是在模块中完全没问题?

您可能会覆盖您的原生 dir 函数。

尝试 help(dir) 查看它的来源。

还请注意 inspect 完全按照您的要求进行操作:

import inspect
inspect.getmembers(obj, predicate=inspect.ismethod)