[英]Python: How to count the number of objects created?
我是 Python 的新手。 我的問題是,計算 python 對象數量以跟蹤任何給定時間存在的對象數量的最佳方法是什么? 我想過使用 static 變量。
我已經閱讀了關於 Python 的 static 變量的幾個問答,但我無法弄清楚如何使用靜態方法實現 object 計數。
我的嘗試是這樣的(如下),從我的 C++ 背景來看,我希望這能奏效,但它沒有。 Iis 不是iMenuNumber
一個 static 成員,它應該在每次創建 object 時遞增?
class baseMENUS:
"""A class used to display a Menu"""
iMenuNumber = 0
def __init__ (self, iSize):
self.iMenuNumber = self.iMenuNumber + 1
self.iMenuSize = iSize
def main():
objAutoTester = baseMENUS(MENU_SIZE_1)
....
....
....
objRunATest = baseMENUS(MENU_SIZE_2)
我還沒有寫 delete( del ) 函數(析構函數)。
使用self.__class__.iMenuNumber
或baseMENUS.iMenuNumber
而不是self.iMenuNumber
在 class 而不是實例上設置 var。
此外,Hungarian Notation 不是 Pythonic(實際上,它在所有語言中都很糟糕)——您可能想停止使用它。 有關一些代碼樣式建議,請參閱http://www.python.org/dev/peps/pep-0008/ 。
請注意,上面的兩個答案都是正確的,但它們非常不同。 不僅在您編寫它們的方式上,而且在最終結果中。
如果您曾經從 baseMENUS class 派生,就會出現差異。
在 nm 的解決方案中,計數器對於從 baseMENUS 派生的任何 class 的所有實例都是相同的。 另一方面,在 ThiefMaster 的情況下; 每個從 baseMENUS 派生的不同 class 都會有計數器。
在下面的例子中。 我從 baseMENUS 派生了兩個類。 它們是 AMENUS 和 BMENUS; 我創建了 3 個 AMENUS 實例和 4 個 BMENUS 實例。
當我使用 nm 的方法時,計數器一直上升到 7。
當我使用 ThiefMaster 時,我創建了 2 個計數器。 一個到 3,另一個到 4:
class baseMENUS:
"""A class used to display a Menu"""
iMenuNumber = 0
jMenuNumber = 0
def __init__ (self):
baseMENUS.iMenuNumber = baseMENUS.iMenuNumber + 1
self.__class__.jMenuNumber = self.__class__.jMenuNumber + 1
self.counterNAMEOFCLASS = baseMENUS.iMenuNumber
self.counterclass = self.__class__.jMenuNumber
class AMENUS(baseMENUS):
def __init__(self, ):
super(AMENUS, self).__init__()
class BMENUS(baseMENUS):
def __init__(self, ):
super(BMENUS, self).__init__()
allmenus = [AMENUS() for i in range(0,3)] + [BMENUS() for i in range(0,4)]
[print('Counting using n.m. method:', i.counterNAMEOFCLASS, '. And counting using ThiefMaster method :', i.counterclass) for i in allmenus]
創建的 output 是:
Counting using n.m. method: 1 . And counting using ThiefMaster method : 1
Counting using n.m. method: 2 . And counting using ThiefMaster method : 2
Counting using n.m. method: 3 . And counting using ThiefMaster method : 3
Counting using n.m. method: 4 . And counting using ThiefMaster method : 1
Counting using n.m. method: 5 . And counting using ThiefMaster method : 2
Counting using n.m. method: 6 . And counting using ThiefMaster method : 3
Counting using n.m. method: 7 . And counting using ThiefMaster method : 4
我很抱歉遲到了 5 年才加入討論。 但我覺得這增加了它。
我認為您應該使用baseMENUS.iMenuNumber
而不是self.iMenuNumber
。
我將實施以下
class baseMENUS: """用於顯示菜單的 class"""
iMenuNumber = 0
def __init__ (self, iSize):
baseMENUS.iMenusNumber += 1
self.iMenuSize = iSize
def main():
objAutoTester = baseMENUS(MENU_SIZE_1)
....
....
....
objRunATest = baseMENUS(MENU_SIZE_2)
class obj:
count = 0
def __init__(self,id,name):
self.id = id
self.name = name
obj.count +=1
print(self.id)
print(self.name)
o1 = obj(1,'vin')
o2 = obj(2,'bini')
o3 = obj(3,'lin')
print('object called' ,obj.count)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.