(十二)判断Python中变量是否是函数
2023-09-27 14:26:28 时间
欢迎访问个人网络日志🌹🌹知行空间🌹🌹
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 -
使用inspect.isfunction,
inspect.isfunction(add)
,判断一个对象是否是Python
种用户自定义的函数,支持判断lambda
表达式,但不能够判断built-in
类型的函数。inspect
是Python
中的标准模块,用来检视活动对象,判断对象类型,源文件,源码,检查解释器堆栈等,具体可参考官方文档。 -
使用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
欢迎访问个人网络日志🌹🌹知行空间🌹🌹
参考资料
相关文章
- Python基础知识(九):模块搜索路径【①内置模块②当前目录③程序主目录④pythonpath目录⑤标准链接库目录⑥第三方库目录⑦.pth 文件内容⑧sys.path.append()临时添加目录】
- Python 爬取网页中JavaScript动态添加的内容(二)
- Python的变量以及类型
- python文件之间变量和函数的 获取/调用 的方法
- 【Python基础】变量的引用(进阶) || 函数的参数和返回值的传递 || 可变类型和不可变类型 || 关于哈希的科普
- 第8.34节 《Python类中常用的特殊变量和方法》总结
- 第8.34节 《Python类中常用的特殊变量和方法》总结
- Python中sort、sorted的cmp参数废弃之后使用cmp_to_key实现类似功能
- 零基础自学python?一般人我劝你还是放弃吧!!
- 点云缩放—python open3d
- python attribute creation