python - 每次我调用一个方法时,我都希望值减少 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 任何人都可以帮忙。
解决方案
您的所有变量都是该方法的本地变量。您需要将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
推荐阅读
- python - 在三引号 fstring 中保留缩进
- python - 如何冻结 Keras 图层中的部分权重?
- jquery-select2 - 当我在 select2 代码中添加匹配器时,主题消失了
- python - 创建一个史派西爵士音乐和弦发生器并使用随机分配每个音符的不同概率
- javascript - 如何根据select2 jQuery字段中选择的多个值显示/隐藏div
- emoji - 如何在 gitk 中显示表情符号
- python - 如何在熊猫数据框中使用日期时间索引获取最后 n 行?
- php - regex for a word but avoiding it if they are making another word
- jquery - 如何从 div 中选择一张图片并获取 id 值
- python - 考虑`var = 5`,一旦我为`var`重新分配另一个值,计算机会自动删除值`5`吗?