"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)
source share