Python 內省
使用 內省(introspection) 可以分析函數、變量和物件。
首先,可以使用 help() 全域函數以文件字串(docstrings)的形式獲取文件。
然後,可以使用 print() 函數來獲取關於函數的資訊:
1 2 3 4 5 6
   | def increment(n):     return n + 1
  print(increment)
  # <function increment at 0x7f420e2973a0>
   | 
 
或者物件的資訊:
1 2 3 4 5 6 7 8 9
   | class Dog():     def bark(self):         print('WOF!')
  roger = Dog()
  print(roger)
  # <__main__.Dog object at 0x7f42099d3340>
   | 
 
type() 函數可以提供物件的類型:
1 2 3 4 5 6 7 8 9 10 11
   | print(type(increment)) # <class 'function'>
  print(type(roger)) # <class '__main__.Dog'>
  print(type(1)) # <class 'int'>
  print(type('test')) # <class 'str'>
   | 
 
dir() 全域函數可以查找物件的所有方法和屬性:
1 2 3
   | print(dir(roger))
  # ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bark']
   | 
 
id() 全域函數可以顯示任何物件在記憶體中的位置:
1 2
   | print(id(roger)) # 140227518093024 print(id(1)) # 140227521172384
   | 
 
這可以用來檢查兩個變數是否指向同一個物件。
Python 的標準庫模組 inspect 提供了更多獲取物件資訊的工具,可以在這裡查看詳細內容:https://docs.python.org/3/library/inspect.html
tags: [“Python”, “introspection”, “type”, “dir”, “id”, “inspect”]