gpt4 book ai didi

python - Hook 在 python 中从列表中添加/删除项目

转载 作者:太空狗 更新时间:2023-10-30 02:23:10 25 4
gpt4 key购买 nike

我想为 python 的 list 创建一个替代品,这样我就可以知道何时添加或删除了一个项目。 list 的子类,或实现 list 接口(interface)的东西也同样可以。不过,我更喜欢一种不必重新实现列表的所有功能的解决方案。有没有一种简单的 + 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.

最佳答案

要查看列表中定义了哪些函数,您可以这样做

>>> dir(list)

然后你会看到你可以覆盖什么,试试这个:

class MyList(list):
def __iadd__(self, *arg, **kwargs):
print "Adding"
return list.__iadd__(self, *arg, **kwargs)

您可能需要多做一些才能获得全部。

关于python - Hook 在 python 中从列表中添加/删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5838307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com