在Python中检查活动对象

该模块中的函数提供有关活动对象的有用信息,例如模块,类,方法,函数,代码对象等。这些函数执行类型检查,检索源代码,检查类和函数以及检查解释程序堆栈。

getmembers()-此函数返回名称列表中对象的所有成员,名称对按名称排序。如果提供了可选谓词,则仅包含谓词为其返回真值的成员。getmodulename()−该函数返回由文件路径命名的模块的名称,不包括封装包的名称

我们将使用以下脚本来了解检查模块的行为。

#inspect-example.py
'''This is module docstring'''
def hello():
   '''hello docstring'''
   print ('Hello world')
   return
#class definitions
class parent:
   '''parent docstring'''
   def __init__(self):
      self.var='hello'
   def hello(self):
      print (self.var)
class child(parent):
   def hello(self):
      '''hello function overridden'''      super().hello()
      print ("How are you?")

以。。开始 '__'

>>> import inspect, inspect_example
>>> for k,v in inspect.getmembers(inspect_example):
      if k.startswith('__')==False:print (k,v)
child
hello
parent
>>>

谓词

谓词是应用于检查模块中功能的逻辑条件。例如,getmembers()函数返回给定谓词条件为true的模块成员的列表。在检查模块中定义了以下谓词

ismodule()如果对象是模块,则返回true。
isclass()如果对象是一个类,无论是内置的还是用Python代码创建的,则返回true。
ismethod()如果对象是用Python编写的绑定方法,则返回true。
isfunction()如果对象是Python函数(包括由lambda表达式创建的函数),则返回true。
isgenerator()如果对象是生成器,则返回true。
iscode()如果对象是代码,则返回true。
isbuiltin()如果对象是内置函数或绑定的内置方法,则返回true。
isabstract()如果对象是抽象基类,则返回true。

这里仅返回模块中的类成员。

>>> for k,v in inspect.getmembers(inspect_example, inspect.isclass):
      print (k,v)
child <class 'inspect_example.child'>
parent <class 'inspect_example.parent'>
>>>

检索指定类'child'的成员-

>>> inspect.getmembers(inspect_example.child)
>>> x=inspect_example.child()
>>> inspect.getmembers(x)

getdoc()函数检索模块,类或函数的文档字符串。

>>> inspect.getdoc(inspect_example)
'This is module docstring'
>>> inspect.getdoc(inspect_example.parent)
'parent docstring'
>>> inspect.getdoc(inspect_example.hello)
'hello docstring'

getsource()函数获取一个函数的定义代码-

>>> print (inspect.getsource(inspect_example.hello))
def hello():
   '''hello docstring'''
   print ('Hello world')
   return
>>> sign=inspect.signature(inspect_example.parent.hello)
>>> print (sign)

检查模块还具有命令行界面。

C:\Users\acer>python -m inspect -d inspect_example
Target: inspect_example
Origin: C:\python36\inspect_example.py
Cached: C:\python36\__pycache__\inspect_example.cpython-36.pyc
Loader: <_frozen_importlib_external.SourceFileLoader object at
0x0000029827BD0D30>

以下命令返回模块中“ Hello()”函数的源代码。

C:\Users\acer>python -m inspect inspect_example:hello
def hello():
   '''hello docstring'''
   print ('Hello world')
   return