# 1.判断函数类型
使用hasattr,
hasattr(add, '__call__')
,function
和可调用的类函数类型都包含__call__
属性,可以使用hasattr和callable
判断对象是否支持调用,返回为true
的对象,不一定是函数。使用isinstance,
isinstance(add, types.FunctionType)
,types.FunctionType
判断是否是用户定义的函数类型,此外还可以使用types.LambdaType
。types
中判断内建函数使用types.BuiltinFunctionType
,判断是否是类种的方法使用types.MethodType
。更多的介绍可以参考doc (opens new window)使用inspect.isfunction,
inspect.isfunction(add)
,判断一个对象是否是Python
种用户自定义的函数,支持判断lambda
表达式,但不能够判断built-in
类型的函数。inspect
是Python
中的标准模块,用来检视活动对象,判断对象类型,源文件,源码,检查解释器堆栈等,具体可参考官方文档 (opens new window)。使用callable,
callable(add)
,callable
是Python
中的内置函数,判断一个对象是否可调用,类可调用返回一个实例,实例可调用,如果其中定义了__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