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

2024-04-26 13:54:10 发布

您现在位置:Python中文网/ 问答频道 /正文

如果这是我的代码:

x = 1
x = 2
x = 3

我怎样才能“记录”这些东西x并将它们打印出来?如果我的解释是愚蠢的,那么以下是我所期望的:

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

我怎样才能做到这一点?你知道吗


Tags: theto代码记录codehasprintbeen
2条回答

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

#!/usr/bin/env/python3

class ValueWithHistory():

    def __init__(self):
        self.history = []
        self._value = None

    @property
    def value(self):
        return self._value

    @value.setter
    def value(self, new_value):
        self.history.append(new_value)
        self._value = new_value

    def get_history(self):
        return self.history

    def clear_history(self):
        self.history.clear()


def main():
    test = ValueWithHistory()
    test.value = 1
    print(test.value)
    test.value = 2
    print(test.value)
    test.value = 3
    print(test.value)
    print(test.get_history())


if __name__ == '__main__':
    main()

这张照片:

1
2
3
[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)

在运行时的任何时刻

相关问题 更多 >