How to determine the number of objects that exist for a particular class?

What is the best way to return the number of existing class objects?

For example, if I built 4 MyClass objects, then the return value should be 4. My personal use for this is an identification system. I want the class constructor to assign the next identification number each time a new class object is built.

Thank you in advance for any guidance!

+4
source share
2 answers

The easiest way is to simply control the counter in the class area:

import itertools class MyClass(object): get_next_id = itertools.count().next def __init__(self): self.id = self.get_next_id() 

This will assign a new identifier for each instance:

 >>> MyClass().id 0 >>> MyClass().id 1 >>> MyClass().id 2 >>> MyClass().id 3 
+6
source

"What is the best way to return the number of existing class objects?"

The exact answer, which I consider “No way”, is because you cannot make sure if the object created by the class was redesigned by the python garbage collection mechanism.

So, if we really want to know the existing objects, we must first make it existing by holding them on the class level attribute when creating them:

 class AClass(object): __instance = [] def __init__(self): AClass.__instance.append(self) @classmethod def count(cls): return len(cls.__instance) 
+2
source

Source: https://habr.com/ru/post/1402157/


All Articles