Python:如何计算创建的对象数量?
我刚开始学Python。我的问题是,怎样才能最好地计算Python对象的数量,以便随时跟踪当前存在的对象数量?我想到了使用静态变量。
我看过一些关于Python静态变量的问答,但我还是搞不清楚怎么用静态变量来实现对象计数。
我尝试了下面的代码,之前我学C++的时候以为这样可以,但结果并没有成功。难道iMenuNumber
不是一个静态成员吗?它应该在每次创建对象时递增啊?
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)
我还没有写删除(del)函数(析构函数)。
5 个回答
注意到上面两个答案都是对的,但它们之间差别很大。不仅在写法上不同,最终的结果也不一样。
这种差别在你从baseMENUS类派生出新类时就会显现出来。
在n.m.的解决方案中,计数器对于从baseMENUS派生的所有类实例都是相同的。而在ThiefMaster的方案中,每个从baseMENUS派生的不同类都有自己的计数器。
下面的例子中,我从baseMENUS派生了两个类,分别是AMENUS和BMENUS;我创建了3个AMENUS的实例和4个BMENUS的实例。
当我使用n.m的方法时,计数器的值会一直增加到7。
而使用ThiefMaster的方法时,我会创建两个计数器。一个计数器的值到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]
生成的输出是:
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
。
使用 self.__class__.iMenuNumber
或 baseMENUS.iMenuNumber
来设置这个变量在类上,而不是在实例上。也就是说,你要把这个变量放在整个类里,而不是某个具体的对象里。
另外,匈牙利命名法在Python中并不推荐(其实在所有语言中都不太好)——你可能要考虑停止使用它。可以查看 http://www.python.org/dev/peps/pep-0008/ 来获取一些代码风格的建议。