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

发布于 2024-11-10 05:46:04 字数 607 浏览 2 评论 0原文

我是Python新手。我的问题是,计算 python 对象数量以跟踪任何给定时间存在的对象数量的最佳方法是什么?我想到使用静态变量。

我读过几篇问答。关于Python的静态变量,但我不知道如何使用静态来实现对象计数。

我的尝试是这样的(如下),从我的 C++ 背景来看,我希望它能起作用,但它没有。 i 不是 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)函数(析构函数)。

I'm new to 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? I thought of using a static variable.

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.

My attempt was like this(below), from my C++ background I was expecting this to work but it didn't. Iis not iMenuNumber a static member and it should get incremented every time an object is created?

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

影子的影子 2024-11-17 05:46:04

使用 self.__class__.iMenuNumberbaseMENUS.iMenuNumber 而不是 self.iMenuNumber 在类而不是实例上设置 var。

另外,匈牙利表示法不是Pythonic的(实际上,它在所有语言中都很糟糕)——你可能想停止使用它。请参阅http://www.python.org/dev/peps/pep-0008/< /a> 一些代码风格建议。

Use self.__class__.iMenuNumber or baseMENUS.iMenuNumber instead of self.iMenuNumber to set the var on the class instead of the instance.

Additionally, Hungarian Notation is not pythonic (actually, it sucks in all languages) - you might want to stop using it. See http://www.python.org/dev/peps/pep-0008/ for some code style suggestions.

維他命╮ 2024-11-17 05:46:04

我认为你应该使用baseMENUS.iMenuNumber而不是self.iMenuNumber

I think you should use baseMENUS.iMenuNumber instead of self.iMenuNumber.

箹锭⒈辈孓 2024-11-17 05:46:04

请注意,上面的两个答案都是正确的,但它们有很大不同。不仅在你编写它们的方式上,而且在最终的结果上。

如果您从 baseMENUS 类派生,就会出现差异。

在 nm 的解决方案中,对于从 baseMENUS 派生的任何类的所有实例化,计数器都将相同。另一方面,就《ThiefMaster》而言;从 baseMENUS 派生的每个不同类都会有一个计数器。

在下面的例子中。我从 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]

创建的输出是:

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 年才进入讨论。但我觉得这增加了它。

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.

In n.m.'s solution, the counter will be the same for ALL instantiations of any class derived from baseMENUS. In the case of ThiefMaster on the other hand; there will be counter for each different class derived from baseMENUS.

In the example below. I derive two classes from baseMENUS. They are AMENUS and BMENUS; I create 3 instances of AMENUS and 4 instances of BMENUS.

When I use n.m's method, The counter goes all the way up to 7.

When I use ThiefMaster's I create 2 counters. One goes to 3 and the other one to 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:

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. But I felt like this added to it.

趁微风不噪 2024-11-17 05:46:04
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)
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)
滥情空心 2024-11-17 05:46:04

我将实现以下

类 baseMENUS:
"""用于显示菜单的类"""

iMenuNumber = 0

def __init__ (self, iSize):
    baseMENUS.iMenusNumber += 1
    self.iMenuSize = iSize

def main():
   objAutoTester = baseMENUS(MENU_SIZE_1)
   ....
   ....
   ....
   objRunATest = baseMENUS(MENU_SIZE_2)

I would implement the following

class baseMENUS:
"""A class used to display a Menu"""

iMenuNumber = 0

def __init__ (self, iSize):
    baseMENUS.iMenusNumber += 1
    self.iMenuSize = iSize

def main():
   objAutoTester = baseMENUS(MENU_SIZE_1)
   ....
   ....
   ....
   objRunATest = baseMENUS(MENU_SIZE_2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文