gpt4 book ai didi

python - dir() 不会使用它的参数

转载 作者:行者123 更新时间:2023-11-30 23:06:24 26 4
gpt4 key购买 nike

我想用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]

我收到一个错误:“类型错误:dir() 不接受任何参数(给定 1 个参数)。”哪里有问题?为什么在 REPL 中编写它完全没问题,但在模块中却不行?

最佳答案

您可能会覆盖 native dir 函数。

尝试help(dir)看看它来自哪里。

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

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

关于python - dir() 不会使用它的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32695956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com