David Gay
David Gay

Reputation: 1154

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

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!

Upvotes: 4

Views: 608

Answers (2)

Reorx
Reorx

Reputation: 3001

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

Upvotes: 2

Niklas B.
Niklas B.

Reputation: 95298

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

Upvotes: 6

Related Questions