Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中从列表中添加/删除项目_Python_List - Fatal编程技术网

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

在python中从列表中添加/删除项目,python,list,Python,List,我想为python的列表创建一个drop-in替换,它允许我知道何时添加或删除某个项。list的子类或实现list接口的东西也同样适用。我更喜欢一个不需要重新实现列表所有功能的解决方案。有没有一个简单的+蟒蛇式的方法 伪代码: class MyList(list): # ... def on_add(self, items): print "Added:" for i in items: print i # and

我想为python的
列表
创建一个drop-in替换,它允许我知道何时添加或删除某个项。list的子类或实现list接口的东西也同样适用。我更喜欢一个不需要重新实现列表所有功能的解决方案。有没有一个简单的+蟒蛇式的方法

伪代码:

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.

告诉您子类化
list
,如果您不需要您的代码与Python一起工作来查看列表中定义了哪些函数,您可以这样做

>>> dir(list)
然后,您将看到可以覆盖的内容,例如:

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

你可能还需要多做几项才能全部完成。

我认为你需要覆盖
追加
扩展
和(有点棘手)
\uuuuuuu设置项
。而不是覆盖
列表
(这是正确的做法,但有点棘手),您可以在一个列表上编写一个小包装器,只实现所需的API。我尝试了
\uuuu setitem\uuuuuu
,想知道为什么控件没有遵循这一点。