What is the best way to return the number of existing objects of a class?
For instance, if I have constructed 4 MyClass objects, then the returned value should be 4. My personal use for this is an ID system. I want a class's constructor to assign the next ID number each time a new object of the class is constructed.
Thanks in advance for any guidance!
The easiest way would be to just manage a counter in the class scope:
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 ID to every instance:
>>> MyClass().id
0
>>> MyClass().id
1
>>> MyClass().id
2
>>> MyClass().id
3
"What is the best way to return the number of existing objects of a class?"
The exact answer I think is "There is no way" because you can not make sure whether the object that created by the class has been recycled by python's garbage collection mechanism.
So if we really want to know the existing objects, we first should make it existing by holding them on a class level attribute when they are created:
class AClass(object):
__instance = []
def __init__(self):
AClass.__instance.append(self)
@classmethod
def count(cls):
return len(cls.__instance)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With