Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-记录字符串以前使用过的内容_Python_Python 3.x - Fatal编程技术网

Python-记录字符串以前使用过的内容

Python-记录字符串以前使用过的内容,python,python-3.x,Python,Python 3.x,如果这是我的代码: x = 1 x = 2 x = 3 我如何“记录”已经发生的事情并打印它们?如果我的解释是愚蠢的,那么以下是我的预期: >>> # Code to print the things x has been 1, 2, 3 >>> 如何实现这一点?您可以订购第二个线程来观察字符串并打印更改: from threading import Thread def string_watcher(): global my_string

如果这是我的代码:

x = 1
x = 2
x = 3
我如何“记录”已经发生的事情并打印它们?如果我的解释是愚蠢的,那么以下是我的预期:

>>> # Code to print the things x has been
1, 2, 3
>>>

如何实现这一点?

您可以订购第二个线程来观察字符串并打印更改:

from threading import Thread
def string_watcher():
    global my_string
    global log
    temp = ''
    while True:
        if my_string != temp:
            log.append(my_string)
            temp = my_string

t = Thread(target=string_watcher, daemon=True)
t.start()
这将检查字符串“my_string”是否被操纵,并将其添加到列表“log”中(如果已更改)。通过此操作,您应该能够执行

Print(log)

在运行时的任何时刻

由于赋值会覆盖对象的值(在您的示例“x”中),因此不可能完全按照您的要求执行操作。但是,您可以创建一个对象,该对象的值可以更改,其历史记录可以记住。例如:

!/usr/bin/env/python3
类值WithHistory():
定义初始化(自):
self.history=[]
self.\u值=无
@财产
def值(自身):
返回自我值
@价值设定者
def值(自身、新_值):
self.history.append(新值)
自我价值=新价值
def获取_历史记录(自我):
回归自我历史
def清除_历史记录(自身):
self.history.clear()
def main():
测试=值WithHistory()
test.value=1
打印(测试值)
test.value=2
打印(测试值)
测试值=3
打印(测试值)
打印(test.get_history())
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
这张照片是:

1
2
3
[1, 2, 3]

当然,您也可以使用集合而不是列表来只记住每个唯一的值一次,例如。

线程根本无法确保捕获所有更改,并且此代码可以轻松地将不同的值附加到列表中,而不是观察到的“更改”值