Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine the number of objects that exist of a specific class?

Tags:

python

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!

like image 392
David Gay Avatar asked Feb 22 '23 02:02

David Gay


2 Answers

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
like image 134
Niklas B. Avatar answered Apr 20 '23 00:04

Niklas B.


"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)
like image 24
Reorx Avatar answered Apr 19 '23 23:04

Reorx