python - 添加事件到列表

标签 python

我想将事件添加到列表中,以便在添加项目时根据项目执行操作,例如生成新的数据结构、更改屏幕输出或引发异常。

我该如何实现?

最佳答案

您可以创建自己的类来扩展列表对象:

class myList(list):
    def myAppend(self, item):
        if isinstance(item, list):
            print 'Appending a list'
            self.append(item)
        elif isinstance(item, str):
            print 'Appending a string item'
            self.append(item)
        else:
            raise Exception

L = myList()
L.myAppend([1,2,3])
L.myAppend('one two three')
print L

#Output:
#Appending a list
#Appending a string item
#[[1, 2, 3], 'one two three']

关于python - 添加事件到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/705296/

相关文章:

python - 我需要在简单的随机数字游戏中修复ValueError的帮助

python - 如何使用Python查找哈夫曼树中父节点的值

python - Pandas DataFrame 使用 where() 将列与阈值列进行比较

python - numpy 数组的 zip_longest

python - 在日期时间中添加特定天数。如何指定格式?

python - 如何检查键变量是否存在并防止在 jinja2 模板中打印键+值为空的行

python - 如何在图像中找到数字并读取它们?

python - scikit learn安装难度

python - 基于列值和变量合成一个 numpy 数组/矩阵?

python - 填充用户名和密码时,selenium python 中的元素不难处理