【发布时间】:2022-01-09 19:04:05
【问题描述】:
我有这个练习,我需要减少一个类属性值(值总是> = 0),然后恢复到原始值。我尝试只计算“-= 1”的次数,但如果该方法继续运行,那么我无法获得正确的“计数”。请看代码:
# Tee ratkaisusi tähän:
class DecreasingCounter:
def __init__(self, initial_value: int):
self.value = initial_value
def print_value(self):
print("value:", self.value)
def decrease(self):
global count
count = 0
if self.value > 0:
self.value -= 1
count += 1
else:
self.value == 0
def set_to_zero(self):
self.value -= self.value
return True
def reset_original_value(self):
self.value += count
# Write the rest of the methods here!
if __name__ == "__main__":
counter = DecreasingCounter(5)
counter.decrease()
counter.decrease()
counter.decrease()
counter.print_value()
counter.reset_original_value()
counter.print_value()
正如您在第三次运行 counter.decrease() 时看到的那样,我的 count 回到“0”。
如何导出权限count?
【问题讨论】:
-
也许你应该有一个
initial_value和一个current_value成员变量。 -
有一个更简单的方法。当您可以轻松撕毁
initial_value时,为什么还要跟踪count?同样对于set_to_zero,为什么不只是self.value = 0?
标签: python class global-variables