3 回答

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
您的所有變量都是該方法的本地變量。您需要將count狀態(tài)存儲(chǔ)在類或?qū)嵗?。您調(diào)用該方法的方式表明您在后者之后:
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貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是你想要的嗎?我認(rèn)為一個(gè)循環(huán)會(huì)更好,但我不知道你想要實(shí)現(xiàn)什么。
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貢獻(xiàn)1788條經(jīng)驗(yàn) 獲得超4個(gè)贊
是的,有很多方法可以實(shí)現(xiàn)這一目標(biāo)!
最簡(jiǎn)單的方法是self.max_count = updated_count
在計(jì)算 updated_count 后添加。您還需要訪問(wèn)max_count
始終使用self.max_count
添加回答
舉報(bào)