Python 類別屬性 (Class Attribute) 與實例屬性 (Instance Attribute) 的查找順序、遮蔽機制與修改行為是面試常考、實務易錯的重點。本文透過互動式範例詳細剖析。
ClassName.attr 存取,所有實例共享同一記憶體位址。__init__ 或動態新增於實例,透過 instance.attr 存取,各實例獨立。__dict__ → 類別 __dict__ → 父類別 __dict__... (MRO)。>> class Test:
... ver = 1
...
>>> a = Test()
>>> Test.x = 8 # 動態新增類別屬性
>>> a.__dict__ # 實例無 x
{}
>>> a.x # 向上查找到類別屬性
8
>>> a.x = 9 # 在實例建立 x (遮蔽類別屬性)
>>> a.__dict__
{'x': 9}
>>> Test.x # 類別屬性不變
8
class Counter:
count = 0
def __init__(self):
Counter.count += 1 # 明確指定類別名
def howmany(self):
print(Counter.count) # 讀取類別屬性
class WrongCounter:
count = 0
def __init__(self):
self.count += 1 # 在實例建立 count,遮蔽類別屬性!
def howmany(self):
print(self.count) # 只印實例自己的 count (永遠為 1)
class ClassProperty:
def __init__(self, fget):
self.fget = fget
def __get__(self, instance, owner):
return self.fget(owner)
class MyClass:
_value = 10
@ClassProperty
def value(cls):
return cls._value
print(MyClass.value) # 10
# MyClass.value = 20 # AttributeError: can't set attribute
MAX_SIZE)。__init__ 設定 self.attr。__init__ 中對可變類別屬性 (list/dict) 直接 append:會影響所有實例!__init__ 中 self.attr = default_value (不可變) 或 self.attr = default_value.copy() (可變)。
Class Test:
x = 10 ← 類別 __dict__['x'] → int(10)
a = Test()
a.x = 20 ← a.__dict__['x'] → int(20) (遮蔽)
b = Test()
b.x ← 找不到 b.__dict__['x'] → 類別 __dict__['x'] → 10
徹底理解屬性查找機制,能避免 90% 的「狀態洩漏」Bug。