我想创建一个Python list
的替代品,可以让我知道何时添加或删除了项目。一个list
子类或实现列表接口的其他方案同样适用。尽管我更喜欢不必重新实现所有list
功能的解决方案。有没有一种简单且符合 Python 风格的方法?
伪代码:
class MyList(list):
# ...
def on_add(self, items):
print "Added:"
for i in items:
print i
# and the same for on_remove
l = MyList()
l += [1,2,3]
# etc.
append
,extend
和(有点棘手的)__setitem__
方法。 - Thomas Klist
(虽然这是正确的做法,但有点棘手),你可以编写一个小包装器,它只实现你需要的API。 - static_rtti