class A():
count = 0
def __init__(self):
A.count += 1
def exclaim(self):
print("I'm an A!")
@classmethod
def kids(cls):
print("A has", cls.count, "little objects.")
easy_a = A()
breezy_a = A()
wheezy_a = A()
A.kids()
print(easy_a.count)
輸出:
A has 3 little objects.
3
類屬性count記錄了類A被實例化了多少次,相當於A這個“抽象類”的屬性,而每一個實例都會得到這個count,所以easy_a.count的值也是3。
如果把count改為初始化時只修改實例的count值,那麼A的count始終是0,而各個實例的count是1。
class A():
count = 0
def __init__(self):
self.count += 1
def exclaim(self):
print("I'm an A!")
@classmethod
def kids(cls):
print("A has", cls.count, "little objects.")
easy_a = A()
breezy_a = A()
wheezy_a = A()
A.kids()
print(easy_a.count)
輸出:
A has 0 little objects.
1
參考資料:《Python語言及其應用》【美】盧巴諾維奇 著