首页 > 解决方案 > 每次我调用一个方法时,我都希望值减少 1

问题描述

有没有一种方法可以在每次调用该方法时将值减少 1。

我试过的代码是

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)

我期望的结果是当第一次调用该方法时,我期望 O/P 为:5 4 4 第二次调用该方法时,我期望 O/P 为:4 3 3 任何人都可以帮忙。

标签: python

解决方案


您的所有变量都是该方法的本地变量。您需要将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

推荐阅读