简体   繁体   English

有没有办法检查何时将某些内容添加到列表中,例如“a=[]”

[英]Is there a way to check when something is added to a list like "a=[]"

I want to print something whenever something is added to a list that I've defined earlier in the code.每当将某些内容添加到我之前在代码中定义的列表中时,我都想打印一些内容。 How do I go about doing this?我该怎么做?

a = []

Couldn't find anything on Google about this在 Google 上找不到关于此的任何信息

There's no built-in way to do this, but you can very easily make your list a user-defined class inheriting from list and hook into the append method:没有内置的方法可以做到这一点,但您可以非常轻松地将您的列表设为一个用户定义的类,该类继承自list并挂接到 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM