Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to count the number of objects created?

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

like image 951
HaggarTheHorrible Avatar asked May 30 '11 17:05

HaggarTheHorrible


2 Answers

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.

like image 64
ThiefMaster Avatar answered Sep 30 '22 04:09

ThiefMaster


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

like image 35
n. 1.8e9-where's-my-share m. Avatar answered Sep 30 '22 05:09

n. 1.8e9-where's-my-share m.