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.

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

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值