gpt4 book ai didi

python - 如果对象是任何函数类型,是否有一种通用的方法来检查 Python?

转载 作者:太空狗 更新时间:2023-10-29 22:03:19 25 4
gpt4 key购买 nike

我在 Python 中有一个函数,它迭代从 dir(obj) 返回的属性,我想检查其中包含的任何对象是否是一个函数、方法、构建-in 函数等。通常您可以为此使用 callable(),但我不想包含类。到目前为止我想到的最好的是:

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))

是否有更面向 future 的方法来进行此检查?

编辑:我之前说错了:“通常你可以为此使用 callable(),但我不想取消类的资格。”实际上,我确实想取消类(class)资格。我只想匹配 函数,而不是类。

最佳答案

inspect 模块正是您想要的:

inspect.isroutine( obj )

仅供引用,代码是:

def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object))

关于python - 如果对象是任何函数类型,是否有一种通用的方法来检查 Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74092/

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