首页 > 解决方案 > Python如何知道列表是否已被修改

问题描述

对不起,误导性的标题和新手问题。在以下代码中:

lst = [1, 2, 3]
idlst_init = id(lst)

lst.append(4)
del lst[lst.index(4)]

idlst_final = id(lst)

print(idlst_init == idlst_final)
# True

是否有任何编程方式(除了查看代码)来评估某些操作是使用 list 执行的lst。使用id()内置显示它是同一个对象,但是甚至可以知道对象修改的“历史”吗?

标签: pythonlistobject

解决方案


您可以通过子类化collections.UserList来创建自己的类。一个例子:

import collections

class myList(collections.UserList):
    def __init__(self, l=None):
        super().__init__(l or [])
        self.edits = []

    def append(self, el):
        super().append(el)
        self.edits.append(f"added {el}")

    def __delitem__(self, idx):
        super().__delitem__(idx)
        self.edits.append(f"removed element at index {idx}")
        
    def clear(self):
        super().clear()
        self.edits.append('cleared')

l = myList([1,2,3])
l.append(1)
del l[0]
l.clear()
print(l.__dict__) # {'data': [], 'edits': ['added 1', 'removed element at index 0', 'cleared']}

推荐阅读