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
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
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
579 Understanding How to Configure Google API Key
615 GDB gets version error when attempting to debug with the Presense SDK (IDE)
925 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
624 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.