[Python] How to calculate the number of objects belonging to the class

Asked 2 years ago, Updated 2 years ago, 137 views

It's exactly what the title is.

class MyCounter:
    def __init__(self, value=0):
        self.counter = value
        pass
    def number_of_counters():
        return ~~~~

c1 = MyCounter()
print(MyCounter.number_of_counters())
c2 = MyCounter(1)
print(MyCounter.number_of_counters())
c3 = MyCounter(2)
print(MyCounter.number_of_counters())

From the above code

1
2
3

What method should I use to get the result of?

python3.6.1 class

2022-09-22 15:54

2 Answers

Well, looking at the code I wrote, I think I need to study a lot.

Learn about the differences between instance variables and class variables.

class MyCounter:
    def __init__(self, value=0):
        self.counter = value + 1
        pass
    def number_of_counters(self):
        return self.counter

c1 = MyCounter()
print(c1.number_of_counters())
c2 = MyCounter(1)
print(c2.number_of_counters())
c3 = MyCounter(2)
print(c3.number_of_counters())

1
2
3
class MyCounter:
    counter = 0
    def __init__(self, value=0):
        MyCounter.counter = value + 1
        pass
    def number_of_counters():
        return MyCounter.counter

c1 = MyCounter()
print(MyCounter.number_of_counters())
c2 = MyCounter(1)
print(MyCounter.number_of_counters())
c3 = MyCounter(2)
print(MyCounter.number_of_counters())

1
2
3


2022-09-22 15:54

I don't understand exactly what the question means If you understand by checking the number of objects created by a particular class on the code, you can add return cnt to the second code below and put it in 'def number_of_counters(self)...

class A():
    pass

a = A()
b = A()
c = A()
cnt = 0
for n in range(len(dir())):
    ifisinstance(val("%s" %dir()[n]), A(class name): cnt = cnt + 1
>>> cnt
3


2022-09-22 15:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.