Skip to main content
 首页 » 编程设计

python之添加事件到列表

2025年05月04日10xxx_UU

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

我该如何实现?

请您参考如下方法:

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

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