函數,變量和對象可以使用內省。
首先,使用help()
如果以docstring的形式提供,則可以獲取全局函數的文檔。
然後,您可以使用print()獲取有關函數的信息:
def increment(n):
return n + 1
print(increment)
# <function increment at 0x7f420e2973a0>
或對象:
class Dog():
def bark(self):
print('WOF!')
roger = Dog()
print(roger)
# <main.Dog object at 0x7f42099d3340>
這type()
函數為我們提供了對象的類型:
print(type(increment))
# <class 'function'>
print(type(roger))
# <class ‘main.Dog’>
print(type(1))
# <class ‘int’>
print(type(‘test’))
# <class ‘str’>
這dir()
全局函數使我們能夠找到對象的所有方法和屬性:
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()
全局函數向我們顯示了任何對像在內存中的位置:
print(id(roger)) # 140227518093024
print(id(1)) # 140227521172384
檢查兩個變量是否指向同一對象可能很有用。
這inspect
標準庫模塊為我們提供了更多工具來獲取有關對象的信息,您可以在此處進行查看:https://docs.python.org/3/library/inspect.html
更多python教程:
- Python簡介
- 在macOS上安裝Python 3
- 運行Python程序
- Python 2和Python 3
- 使用Python的基礎
- Python數據類型
- Python運算子
- Python字符串
- Python布爾值
- Python數字
- Python,接受輸入
- Python控制語句
- Python列表
- Python元組
- Python集
- Python字典
- Python函數
- Python對象
- Python循環
- Python模塊
- Python類
- Python標準庫
- 調試Python
- Python變量範圍
- Python,從命令行接受參數
- Python遞歸
- Python嵌套函數
- Python Lambda函數
- Python閉包
- Python虛擬環境
- 使用Python將GoPro用作遠程網絡攝像頭
- Python,如何從字符串創建列表
- Python裝飾器
- Python Docstrings
- Python自省
- Python註釋
- Python,如何列出目錄中的文件和文件夾
- Python,如何檢查數字是否為奇數或偶數
- Python,如何獲取文件的詳細信息
- Python,如何檢查文件或目錄是否存在
- Python異常
- Python,如何創建目錄
- Python,如何創建一個空文件
- Python,`with`語句
- Python,創建網絡請求
- Python,使用`pip`安裝第三方軟件包
- Python,讀取文件內容