问题描述
我是Python的新手。我的问题是,计算python对象数量以跟踪在任何给定时间存在的对象数量的最佳方法是什么?我想到要使用静态变量。
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.
我已经阅读了几个Q&关于Python的静态变量,但是我无法弄清楚如何使用静态变量来实现对象计数。
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.
我的尝试是这样的(如下),来自C ++背景我原以为这会成功,但没有成功。我不是 iMenuNumber
的静态成员,并且每次创建对象时它应该增加吗?
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)
我还没有编写delete( del )函数(析构函数)。
I'm yet to write the delete(del) function(destructor).
推荐答案
使用 self .__ class __。iMenuNumber
或 baseMENUS.iMenuNumber
代替 self.iMenuNumber
可以在类而不是实例上设置var。
Use self.__class__.iMenuNumber
or baseMENUS.iMenuNumber
instead of self.iMenuNumber
to set the var on the class instead of the instance.
此外,匈牙利表示法不是pythonic(实际上,它会以各种语言显示)-您可能要停止使用它。参见获得一些代码样式建议。
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.
这篇关于Python:如何计算创建的对象数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!