Python 将事件添加到列表中

Python 将事件添加到列表中,python,Python,我想将事件添加到列表中,以便在添加项目时根据项目采取行动,例如生成新的数据结构、更改屏幕输出或引发异常 如何实现这一点?您可以创建自己的类来扩展列表对象: class myList(list): def myAppend(self, item): if isinstance(item, list): print 'Appending a list' self.append(item) elif isinsta

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


如何实现这一点?

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

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']

+1... 但是不需要调用方法“myAppend”。。。使用普通的append方法名可能更好,只需调用超类append来实现实际的append