我想获取变量的最新值,而不是获取初始值。 如何获取最新的值? 另外,如果是由于字符串的不可变性质,那么在不影响字符串变量的使用的情况下,有什么解决方法。
以下是简单的Python代码-
class Example:
def __init__(self):
self.vr = '' # initial value (blank/none)
def input_value(self):
self.vr = 'Hello' # latest value (Hello string)
def return_value(self):
return self.vr # want to return the above latest value (i.e, Hello)
if __name__ == '__main__':
Example().input_value()
cp = Example().return_value()
print(cp) # should print 'Hello', instead prints ''
不要丢弃初始实例, 您小心地将值设置为“hello”的那个。
if __name__ == '__main__':
example = Example()
example.input_value() # mutates the `example.vr` attribute
cp = example.return_value() # no idea what `cp` denotes here
print(cp) # will print 'Hello'
这是您所做的,重写以突出显示您可能没有意识到是该过程的一部分的中间步骤:
# Example().input_value()
tmp1 = Example()
tmp1.input_value()
# cp = Example().return_value()
tmp2 = Example()
cp = tmp2.return_value()
这才是你真正想要的:
example = Example()
example.input_value()
cp = example.return_value()