首頁  >  文章  >  後端開發  >  Python 的自省是什麼?

Python 的自省是什麼?

Guanhui
Guanhui轉載
2020-06-22 13:37:302048瀏覽

Python 的自省是什麼?

什麼是自省?

在日常生活中,自省(introspection)是一種自我檢查行為。

在電腦程式設計中,自省是指這種能力:檢查某些事物以確定它是什麼、它知道什麼以及它能做什麼。自省向程式設計師提供了極大的靈活性和控制力。

說的更簡單直白一點:自省就是物件導向的語言所寫的程式在執行時,能夠知道物件的類型。簡單一句就是,運行時能夠獲知物件的類型。

例如python, buby, object-C, c 都有自省的能力,這裡面的c 的自省的能力最弱,只能夠知道是什麼類型,而像python可以知道是什麼類型,還有什麼屬性。

最好的理解自省就是透過例子: Type introspection 這裡是各種程式語言中自省(introspection)的例子(這個連結裡的例子很重要,也許你很難透過敘述理解什麼是introspection,但透過這些例子,一下子你就可以理解了)

回到Python,Python中比較常見的自省(introspection)機制(函數用法)有: dir(),type(), hasattr() , isinstance(),透過這些函數,我們能夠在程式執行時得知物件的類型,判斷物件是否存在某個屬性,存取物件的屬性。

dir()

dir() 函數可能是 Python 自省機制中最著名的部分了。它傳回傳遞給它的任何物件的屬性名稱經過排序的清單。如果不指定對象,則 dir() 傳回目前作用域中的名稱。讓我們將dir() 函數應用於keyword 模組,並觀察它揭示了什麼:


>>> import keyword
>>> dir(keyword)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'iskeyword', 'kwlist', 'main']

type()

##type() 函數有助於我們確定物件是字串還是整數,或是其它類型的物件。它透過傳回類型物件來做到這一點,可以將這個類型物件與types 模組中定義的類型進行比較:


>>> type(42)<class &#39;int&#39;>
>>> type([])<class &#39;list&#39;>

isinstance()

可以使用isinstance() 函數測試對象,以確定它是否是某個特定類型或自訂類別的實例:


>>> isinstance("python", str)
True

Python自省中help用法擴充:

開啟python的IDLE,就進入到了python解釋器中,python解釋器本身是被認為是一個主模組,然後在解釋器提示符>>>下輸入一些我們想了解的信息,所以首先我們會先尋求幫助,所以輸入help,接著輸入help(),我們就進入了help utility,然後循著提示keywords,modules,以了解python的關鍵字以及python自帶的或我們額外安裝和定義的模組,如果要退出,輸入'q',然後回車。

如果我們想了解某個物件(python裡面所有物件都可以認為是物件),也可以求助也help(),不過要在括號裡輸入物件的名稱,格式help(object),例如help(print),鑑於物件的自省內容太多,有的只貼出部分內容。


>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Welcome to Python 3.6&#39;s help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
...
help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

False        def         if         raise
None        del         import       return
True        elif        in         try
and         else        is         while
as         except       lambda       with
assert       finally       nonlocal      yield
break        for         not         
class        from        or         
continue      global       pass        

help> modules

Please wait a moment while I gather a list of all available modules...

PIL         base64       idlelib       runpy
__future__     bdb         idna        runscript
__main__      binascii      idna_ssl      sched
_ast        binhex       imaplib       scrolledlist
_asyncio      bisect       imghdr       search
_bisect       browser       imp         
...
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
>>> help(&#39;print&#39;)
Help on built-in function print in module builtins:

print(...)
  print(value, ..., sep=&#39; &#39;, end=&#39;\n&#39;, file=sys.stdout, flush=False)
  
  Prints the values to a stream, or to sys.stdout by default.
  Optional keyword arguments:
  file: a file-like object (stream); defaults to the current sys.stdout.
  sep:  string inserted between values, default a space.
  end:  string appended after the last value, default a newline.
  flush: whether to forcibly flush the stream.

推薦教學:《

Python教學》《Python教學

以上是Python 的自省是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:jb51.net。如有侵權,請聯絡admin@php.cn刪除