Reputation: 51
Is there a way I can decrease the value by 1 every time I call the method.
The code I tried is
Class Testing:
max_count = 5
def update_count(self, reducebyone):
actual_count = max_count
updated_count = actual_count - reducebyone
resetcount = updated_count
print(actual_count)
print(updated_count)
print(resetcount)
obj = Testing()
obj.update_count(1)
obj.update_count(1)
The result im expecting is when the method called first time I expect the O/P to be : 5 4 4 And second time when the method is called I expect the O/P to be : 4 3 3 Can anyone help in this.
Upvotes: 0
Views: 44
Reputation: 376
Yes there are plenty of ways to achieve this !
The easiest one would be to add self.max_count = updated_count
after you compute updated_count. Also you need to access to max_count
always using self.max_count
Upvotes: 0
Reputation: 73470
All your variables are local to the method. You will need to store the count
state in the class or the instance. The way you invoke the method indicates you are after the latter:
class Testing:
def __init__(self):
self.count = 5
def update_count(self, reducebyone):
print(self.count)
self.count -= reducebyone
print(self.count)
>>> obj = Testing()
>>> obj.update_count(1)
5
4
>>> obj.update_count(1)
4
3
Upvotes: 1
Reputation: 716
Is this is what you wanted? A loop I think would be better, but I don't know what are you trying to achieve.
class Testing:
max_count = 5
cur_count = max_count
def update_count(self, reducebyone):
self.cur_count -= reducebyone
resetcount = self.cur_count
print(self.max_count)
print(self.cur_count)
print(resetcount)
obj = Testing()
obj.update_count(1)
obj.update_count(1)
Output:
5
4
4
5
3
3
Upvotes: 0