在 Python 中檢查活動物件


此模組中的函式提供了有關活動物件(如模組、類、方法、函式、程式碼物件等)的有用資訊。這些函式執行型別檢查、檢索原始碼、檢查類和函式以及檢查直譯器堆疊。

getmembers()− 此函式以名稱-值對列表的形式返回物件的全部成員,並按名稱排序。如果提供了可選的謂詞,則僅包含謂詞返回值為真的成員。getmodulename() −此函式返回由檔案路徑命名的模組的名稱,不包括封閉包的名稱。

我們將使用以下指令碼瞭解 inspect 模組的行為。

#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
>>>

謂詞

謂詞是應用於 inspect 模組中函式的邏輯條件。例如,getmembers() 函式返回給定謂詞條件為真的模組成員列表。以下謂詞在 inspect 模組中定義

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)

inspect 模組還有一個命令列介面。

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

更新於: 2019年7月30日

622 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.