I have this exercise, which I need to decrease a class attributes value(value always >=0), and then restore back to original value. I try to count only the times "-= 1", but if the method keeps operate, then I cannot get the right "count". Please see the code:
# Tee ratkaisusi tähän:
class DecreasingCounter:
def __init__(self, initial_value: int):
self.value = initial_value
def print_value(self):
print("value:", self.value)
def decrease(self):
global count
count = 0
if self.value > 0:
self.value -= 1
count = 1
else:
self.value == 0
def set_to_zero(self):
self.value -= self.value
return True
def reset_original_value(self):
self.value = count
# Write the rest of the methods here!
if __name__ == "__main__":
counter = DecreasingCounter(5)
counter.decrease()
counter.decrease()
counter.decrease()
counter.print_value()
counter.reset_original_value()
counter.print_value()
as you can see when run counter.decrease() the third time, my count back to be "0".
How do I export a right count?
CodePudding user response:
You are quite close! But look what happens with your count:
def decrease(self):
global count
count = 0 # Here!
Every decrease you set count to 0 at first, so count is always 0 or 1. What you want to do is just move it outside the class:
count = 0
class DecreasingCounter:
...
But now you need to remember about reseting that count!
def reset_original_value(self):
global count
self.value = count
count = 0
But if there is a reason it is a global variable? If not, you can just use instance attribute for that:
class DecreasingCounter:
def __init__(self, initial_value: int):
self.value = initial_value
self.count = 0
# or instead of counting calls, use the current_value directly
self.current_value = initial_value
CodePudding user response:
I think it would be simpler to just explicitly maintain both the current and initial values:
class DecreasingCounter:
def __init__(self, initial_value: int):
self.initial_value = initial_value
self.value = initial_value
def print_value(self):
print("value:", self.value)
def decrease(self):
if self.value > 0:
self.value -= 1
def set_to_zero(self):
self.value = 0
def reset_original_value(self):
self.value = self.initial_value
Now you can do:
if __name__ == "__main__":
counter = DecreasingCounter(5)
counter.decrease()
counter.decrease()
counter.decrease()
counter.print_value()
counter.reset_original_value()
counter.print_value()
counter.set_to_zero()
counter.print_value()
counter.decrease()
counter.print_value()
Giving:
value: 2
value: 5
value: 0
value: 0
