我想为python创建一个替代品list,这样我就可以知道添加或删除项目的时间.列表的子类或实现列表接口的东西也同样适用.我更喜欢一个解决方案,我不必重新实现列表的所有功能.有一种简单的+ pythonic方式吗?
伪代码:
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.
Run Code Online (Sandbox Code Playgroud)
要查看列表中定义的功能,您可以执行此操作
>>> dir(list)
Run Code Online (Sandbox Code Playgroud)
然后你会看到你可以覆盖的东西,试试这个:
class MyList(list):
def __iadd__(self, *arg, **kwargs):
print "Adding"
return list.__iadd__(self, *arg, **kwargs)
Run Code Online (Sandbox Code Playgroud)
你可能需要做更多的事情来获得所有这些.
| 归档时间: |
|
| 查看次数: |
535 次 |
| 最近记录: |