Python 是否有一种方法可以检查何时向列表中添加了类似“a=[]”的内容

Python 是否有一种方法可以检查何时向列表中添加了类似“a=[]”的内容,python,Python,每当有东西被添加到我在代码前面定义的列表中时,我想打印一些东西。我该怎么做呢 a=[] 在Google上找不到关于此的任何信息没有内置的方法,但您可以非常轻松地将列表设置为从列表继承的用户定义类,并挂接到append方法中: class MyList(list): def append(self, item): print(f'item {item} will be appended to {str(self)}') return_value = s

每当有东西被添加到我在代码前面定义的列表中时,我想打印一些东西。我该怎么做呢

a=[]
在Google上找不到关于此的任何信息

没有内置的方法,但您可以非常轻松地将列表设置为从列表继承的用户定义类,并挂接到append方法中:

class MyList(list): 
    def append(self, item): 
        print(f'item {item} will be appended to {str(self)}') 
        return_value = super().append(item) 
        print(f'append succeeded -> list is now {str(self)}') 
        return return_value

mylist = MyList('abc')

print(mylist)
# output:
# ['a', 'b', 'c']

mylist.append('d')
# output:
# item d will be appended to ['a', 'b', 'c']
# append succeeded -> list is now ['a', 'b', 'c', 'd']

print(mylist)
# output:
# ['a', 'b', 'c', 'd']

我不认为有任何内在的方法可以做到这一点。您需要为列表实现一个getter/setter来手动监视它。只需检查新列表是否与原始列表相同?您只需在每次添加后检查列表。