# 1.判断函数类型

  • 使用hasattrhasattr(add, '__call__'), function和可调用的类函数类型都包含__call__属性,可以使用hasattr和callable判断对象是否支持调用,返回为true的对象,不一定是函数。

  • 使用isinstanceisinstance(add, types.FunctionType)types.FunctionType判断是否是用户定义的函数类型,此外还可以使用types.LambdaTypetypes中判断内建函数使用types.BuiltinFunctionType,判断是否是类种的方法使用types.MethodType。更多的介绍可以参考doc (opens new window)

  • 使用inspect.isfunctioninspect.isfunction(add),判断一个对象是否是Python种用户自定义的函数,支持判断lambda表达式,但不能够判断built-in类型的函数。inspectPython中的标准模块,用来检视活动对象,判断对象类型,源文件,源码,检查解释器堆栈等,具体可参考官方文档 (opens new window)

  • 使用callablecallable(add),callablePython中的内置函数,判断一个对象是否可调用,类可调用返回一个实例,实例可调用,如果其中定义了__call__方法。

# 2.示例

import types
import inspect

def add(x, y):
    print(x+y)

class Model:
    def __call__(x, y):
        print(f"Model({x}, {y}) is: {x + y}")
        
print("function add:")
print("isinstance(function): ", isinstance(add, types.FunctionType))
print("isinstance(lambda): ", isinstance(add, types.LambdaType))

print("inspect: ", inspect.isfunction(add))
print("callable: ", callable(add))
print("__call__: ", hasattr(add, '__call__'))

print("Callable Model:")
print("isinstance: ", isinstance(Model, types.FunctionType))
print("inspect: ", inspect.isfunction(Model))
print("callable: ", callable(Model))
print("__call__: ", hasattr(Model, '__call__'))

print("buildin print:")
print("isinstance: ", isinstance(print, types.FunctionType))
print("inspect: ", inspect.isfunction(print))
print("callable: ", callable(print))
print("__call__: ", hasattr(print, '__call__'))
print("BuiltinFunctionType:", isinstance(abs, types.BuiltinFunctionType))

# function add:
# isinstance(function):  True
# isinstance(lambda): True

# inspect:  True
# callable:  True
# __call__:  True

# Callable Model:
# isinstance:  False
# inspect:  False
# callable:  True
# __call__:  True

# buildin print:
# isinstance:  False
# inspect:  False
# callable:  True
# __call__:  True
# BuiltinFunctionType: True
(adsbygoogle = window.adsbygoogle || []).push({});
### 参考资料