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

Joe*_*haw 6 python types

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

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))
Run Code Online (Sandbox Code Playgroud)

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

编辑:我错过了之前我说:"通常你可以使用callable(),但我不想取消课程资格." 其实我想取消其参赛资格类.我想匹配函数,而不是类.

小智 13

检查模块正是您想要的:

inspect.isroutine( obj )
Run Code Online (Sandbox Code Playgroud)

仅供参考,代码是:

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))
Run Code Online (Sandbox Code Playgroud)

  • isroutine()为partials返回False.hasattr(obj,'__ call__')为partials返回True. (2认同)

dF.*_*dF. 5

如果要排除可能有__call__方法的类和其他随机对象,并且只检查函数和方法,则模块中的这三个函数inspect

inspect.isfunction(obj)
inspect.isbuiltin(obj)
inspect.ismethod(obj)
Run Code Online (Sandbox Code Playgroud)

应该以面向未来的方式做你想做的事.