简体   繁体   English

Python:如何统计创建的对象数量?

[英]Python: How to count the number of objects created?

I'm new to Python.我是 Python 的新手。 My question is, what is the best way to count the number of python objects for keeping track of number of objects exist at any given time?我的问题是,计算 python 对象数量以跟踪任何给定时间存在的对象数量的最佳方法是什么? I thought of using a static variable.我想过使用 static 变量。

I have read several Q & A on static variables of Python, but I could not figure out how I could achieve object counting using statics.我已经阅读了关于 Python 的 static 变量的几个问答,但我无法弄清楚如何使用静态方法实现 object 计数。

My attempt was like this(below), from my C++ background I was expecting this to work but it didn't.我的尝试是这样的(如下),从我的 C++ 背景来看,我希望这能奏效,但它没有。 Iis not iMenuNumber a static member and it should get incremented every time an object is created? 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)

I'm yet to write the delete( del ) function(destructor).我还没有写 delete( del ) 函数(析构函数)。

Use self.__class__.iMenuNumber or baseMENUS.iMenuNumber instead of self.iMenuNumber to set the var on the class instead of the instance.使用self.__class__.iMenuNumberbaseMENUS.iMenuNumber而不是self.iMenuNumber在 class 而不是实例上设置 var。

Additionally, Hungarian Notation is not pythonic (actually, it sucks in all languages) - you might want to stop using it.此外,Hungarian Notation 不是 Pythonic(实际上,它在所有语言中都很糟糕)——您可能想停止使用它。 See http://www.python.org/dev/peps/pep-0008/ for some code style suggestions.有关一些代码样式建议,请参阅http://www.python.org/dev/peps/pep-0008/

Notice that both answers above are right, but they are very different.请注意,上面的两个答案都是正确的,但它们非常不同。 Not only in the way you write them but in the final result.不仅在您编写它们的方式上,而且在最终结果中。

The difference would come up if you were ever to derive from the baseMENUS class.如果您曾经从 baseMENUS class 派生,就会出现差异。

In nm's solution, the counter will be the same for ALL instantiations of any class derived from baseMENUS.在 nm 的解决方案中,计数器对于从 baseMENUS 派生的任何 class 的所有实例都是相同的。 In the case of ThiefMaster on the other hand;另一方面,在 ThiefMaster 的情况下; there will be counter for each different class derived from baseMENUS.每个从 baseMENUS 派生的不同 class 都会有计数器。

In the example below.在下面的例子中。 I derive two classes from baseMENUS.我从 baseMENUS 派生了两个类。 They are AMENUS and BMENUS;它们是 AMENUS 和 BMENUS; I create 3 instances of AMENUS and 4 instances of BMENUS.我创建了 3 个 AMENUS 实例和 4 个 BMENUS 实例。

When I use nm's method, The counter goes all the way up to 7.当我使用 nm 的方法时,计数器一直上升到 7。

When I use ThiefMaster's I create 2 counters.当我使用 ThiefMaster 时,我创建了 2 个计数器。 One goes to 3 and the other one to 4:一个到 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]

The output created is:创建的 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

I'm sorry to jump in 5 years late into the discussion.我很抱歉迟到了 5 年才加入讨论。 But I felt like this added to it.但我觉得这增加了它。

I think you should use baseMENUS.iMenuNumber instead of self.iMenuNumber .我认为您应该使用baseMENUS.iMenuNumber而不是self.iMenuNumber

I would implement the following我将实施以下

class baseMENUS: """A class used to display a Menu""" 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM