[英]Is there a way to check when something is added to a list like "a=[]"
每當將某些內容添加到我之前在代碼中定義的列表中時,我都想打印一些內容。 我該怎么做?
a = []
在 Google 上找不到關於此的任何信息
沒有內置的方法可以做到這一點,但您可以非常輕松地將您的列表設為一個用戶定義的類,該類繼承自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.