3 回答

TA貢獻2065條經驗 獲得超14個贊
您的所有變量都是該方法的本地變量。您需要將count狀態存儲在類或實例中。您調用該方法的方式表明您在后者之后:
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

TA貢獻1873條經驗 獲得超9個贊
這是你想要的嗎?我認為一個循環會更好,但我不知道你想要實現什么。
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)
輸出:
5
4
4
5
3
3

TA貢獻1788條經驗 獲得超4個贊
是的,有很多方法可以實現這一目標!
最簡單的方法是self.max_count = updated_count
在計算 updated_count 后添加。您還需要訪問max_count
始終使用self.max_count
添加回答
舉報