0

I tried this program:

class Test():
    def __init__(self):
        self.value = 10
        print(self.value)

t = Test()
t2 = Test()

I would like to know how many instances were made from the Test class.

mkrieger1
  • 14,486
  • 4
  • 43
  • 54
Paul Kocian
  • 465
  • 4
  • 19

2 Answers2

1

This should do the job, which you're looking for. Rest you can make a file and print the response. I am just representing the thing which you want for now:

class Test:
    # this is responsible for the count
    counter = 0
    def __init__(self):
        Test.counter += 1
        self.id = Test.counter

t = Test()
t2 = Test()
print(Test.counter)

# OUTPUT => 2
halfer
  • 19,471
  • 17
  • 87
  • 173
Alok
  • 7,392
  • 8
  • 44
  • 82
1

The idea to create a counter for the class and increment them if a new instance is created, works in most cases.

However, you should keep some aspects in mind. What if a instance is removed? There is no mechanism to decrease this counter. To do this, you could use the __del__ method, which is called when the instance is about to be destroyed.

class Test:
    counter = 0
    def __init__(self):
        Test.counter += 1
        self.id = Test.counter
    def __del__(self):
        Test.counter -= 1

But sometimes it can be problematic to find out, when an instance is deleted. In this blog post you can find some more information if needed.

Querenker
  • 2,124
  • 1
  • 17
  • 26