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
  • 19,194
  • 5
  • 54
  • 65
Paul Kocian
  • 487
  • 4
  • 20

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,824
  • 17
  • 99
  • 186
Alok
  • 8,452
  • 13
  • 55
  • 93
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,242
  • 1
  • 18
  • 29