本文主要是介绍python: inspect模块各函数的用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
python: inspect模块各函数的用法
inspect模块也被称为 检查现场对象。这里的重点在于“现场”二字,也就是当前运行的状态。
inspect模块提供了一些函数来了解现场对象,包括 模块、类、实例、函数和方法。
inspect函数主要用于以下四个方面
- 对是否是模块、框架、函数进行类型检查
- 获取源码包
- 获取类或者函数的参数信息
- 解析堆栈
一、inspect模块总览
1、获取成员与判断
- inspect.getmembers(object[, predicate])
第二个参数通常可以根据需要调用如下16个方法;
返回值为object的所有成员,以(name,value)对组成的列表
inspect.ismodule(object): 是否为模块
inspect.isclass(object):是否为类
inspect.ismethod(object):是否为方法(bound method written in python)
inspect.isfunction(object):是否为函数(python function, including lambda expression)
inspect.isgeneratorfunction(object):是否为python生成器函数
inspect.isgenerator(object):是否为生成器
inspect.istraceback(object): 是否为traceback
inspect.isframe(object):是否为frame
inspect.iscode(object):是否为code
inspect.isbuiltin(object):是否为built-in函数或built-in方法
inspect.isroutine(object):是否为用户自定义或者built-in函数或方法
inspect.isabstract(object):是否为抽象基类
inspect.ismethoddescriptor(object):是否为方法标识符
inspect.isdatadescriptor(object):是否为数字标识符,数字标识符有__get__ 和__set__属性; 通常也有__name__和__doc__属性
inspect.isgetsetdescriptor(object):是否为getset descriptor
inspect.ismemberdescriptor(object):是否为member descriptor
- inspect.getmoduleinfo(path): 返回一个命名元组(name, suffix, mode, module_type)
name:模块名(不包括其所在的package)
suffix:mode:open()方法的模式,如:'r', 'a'等module_type: 整数,代表了模块的类型
- inspect.getmodulename(path):根据path返回模块名(不包括其所在的package)
2、获取源代码
-
inspect.getdoc(object): 获取object的documentation信息
-
inspect.getcomments(object)
-
inspect.getfile(object): 返回对象的文件名
-
inspect.getmodule(object):返回object所属的模块名
-
inspect.getsourcefile(object): 返回object的python源文件名;object不能使built-in的module, class, mothod
-
inspect.getsourcelines(object):返回object的python源文件代码的内容,行号+代码行
-
inspect.getsource(object):以string形式返回object的源代码
3、类与函数
-
inspect.getclasstree(classes[, unique])
-
inspect.getargspec(func)
-
inspect.getargvalues(frame)
-
inspect.formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])
-
inspect.formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])
-
inspect.getmro(cls): 元组形式返回cls类的基类(包括cls类),以method resolution顺序;通常cls类为元素的第一个元素
-
inspect.getcallargs(func[, *args][, **kwds]):将args和kwds参数到绑定到为func的参数名;对bound方法,也绑定第一个参数(通常为self)到相应的实例;返回字典,对应参数名及其值;
4、调用栈
-
inspect.getframeinfo(frame[, context])
-
inspect.getouterframes(frame[, context])
-
inspect.getinnerframes(traceback[, context])
-
inspect.currentframe()
-
inspect.stack([context])
-
inspect.trace([context])
这篇关于python: inspect模块各函数的用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!