在 Python 里,我們經常需要檢查一個對象的類型、屬性、方法,甚至它的源碼。這對調試、學習和動態編程特別有用。今天我們就來聊聊獲取對象信息的常見方法,按由淺入深的順序來學習。
參考文章:Python 獲取對象信息 | 簡單一點學習 easyeasy.me
1. 用 type()
查看對象類型
最直接的方法就是 type()
,它會返回對象的類型。
x = 123
print(type(x)) # <class 'int'>y = "Hello"
print(type(y)) # <class 'str'>
適合快速判斷變量屬于什么類型。
2. 用 isinstance()
判斷對象類型
isinstance()
用來判斷對象是否屬于某個類(或其子類)。
x = 3.14
print(isinstance(x, float)) # True
print(isinstance(x, int)) # False# 支持元組,一次判斷多個類型
print(isinstance(x, (int, float))) # True
適合類型分支處理,比
type()
更靈活,因為它會考慮繼承關系。
3. 用 dir()
查看對象所有屬性和方法
dir()
會列出對象的所有屬性和方法(包括繼承的)。
print(dir("abc"))
輸出(部分):
['__add__', '__class__', '__contains__', '__eq__', ...]
小技巧:
dir()
會返回魔法方法(__xxx__
)和普通方法混在一起,可配合filter()
或列表推導篩掉。
4. 用 hasattr()
、getattr()
、setattr()
動態操作屬性
這三個函數能動態檢查、獲取、設置屬性。
class Person:def __init__(self, name):self.name = namep = Person("Tom")print(hasattr(p, "name")) # True
print(getattr(p, "name")) # Tomsetattr(p, "age", 18)
print(p.age) # 18
適合寫通用代碼,比如 JSON ? 對象 轉換。
5. 用 vars()
或 __dict__
查看對象的屬性字典
vars()
會返回對象的 __dict__
屬性(存放實例變量的字典)。
class Car:def __init__(self, brand, price):self.brand = brandself.price = pricec = Car("Tesla", 300000)
print(vars(c)) # {'brand': 'Tesla', 'price': 300000}
print(c.__dict__) # 同樣的結果
注意:內置類型(如
list
)沒有__dict__
,因為它們用__slots__
或 C 實現。
6. 用 callable()
判斷對象是否可調用
可調用對象包括函數、類、實現了 __call__
方法的實例。
print(callable(len)) # True
print(callable("hello")) # False
7. 用 id()
獲取對象的內存地址
id()
返回對象在內存中的唯一標識(CPython 中是地址)。
x = 100
print(id(x)) # 例如 140714563326192
8. 用 help()
獲取對象的文檔說明
help()
會進入交互式幫助,顯示對象的功能和用法。
help(str)
help(str.upper)
在 IDE 或交互式終端特別有用,相當于 Python 自帶文檔查詢。
9. 用 __class__
和 __bases__
查看類信息
class Animal: pass
class Dog(Animal): passd = Dog()
print(d.__class__) # <class '__main__.Dog'>
print(Dog.__bases__) # (<class '__main__.Animal'>,)
10. 用 inspect
模塊獲取更詳細信息(進階)
inspect
是 Python 官方的“對象解剖工具”,功能很全。
import inspectdef foo(a, b=1):"""這是 foo 函數的說明"""return a + bprint(inspect.getsource(foo)) # 獲取源碼
print(inspect.signature(foo)) # 獲取函數簽名
print(inspect.getdoc(foo)) # 獲取文檔字符串
print(inspect.getmodule(foo)) # 獲取所在模塊
常用函數:
inspect.getmembers(obj)
獲取對象所有成員inspect.isfunction(obj)
判斷是否是函數inspect.ismethod(obj)
判斷是否是方法
11. 用 __slots__
限制并查看屬性(特殊場景)
class Point:__slots__ = ("x", "y")def __init__(self, x, y):self.x = xself.y = yp = Point(1, 2)
# print(vars(p)) # 會報錯,因為沒有 __dict__
有些類用
__slots__
節省內存,這時vars()
取不到屬性,需要自己訪問。
12. 用 gc
模塊查看所有對象(調試內存)
import gc
objs = gc.get_objects()
print(len(objs)) # 當前內存里對象的數量
13. 總結
在 Python 中,獲取對象信息的方法從基礎到進階依次是:
type()
/isinstance()
dir()
/hasattr()
/getattr()
/setattr()
vars()
/__dict__
callable()
/id()
/help()
__class__
/__bases__
inspect
模塊(源碼、簽名、文檔)gc
模塊(調試對象)
學會這些方法,你就能像外科醫生一樣“剖析”任何 Python 對象。