2024-04-26 17:19:06 发布
网友
如何在列表中添加内容时进行检测?有没有一个等价于dictionary __setitem__的方法,当通过insert、extend、append或使用+或+=(__add__、__iadd__)或我可能忘记的其他方法将某个内容添加到列表时,该方法将被调用?或者我需要一个接一个地使用这些方法吗?你知道吗
__setitem__
insert
extend
append
+
+=
__add__
__iadd__
正如obskyr的答案所建议的,您必须定义一个子类list,重写许多方法,并仔细测试以确定是否遗漏了某些内容。你知道吗
list
我的方法使用更深层次的钩子,使用__getattribute__(用于方法调用)、__iadd__(用于+=)和__setitem__(用于切片分配)来捕获最大的更改,并调用原始父方法,使其像一般的中间人一样工作:
__getattribute__
class MyList(list): def __getattribute__(self,a): if a in {"append","extend","remove","insert","pop","reverse","sort","clear"}: print("modification by {}".format(a)) else: print("not modified {}".format(a)) return list.__getattribute__(self,a) def __iadd__(self,v): print("in place add") return list.__iadd__(self,v) def __setitem__(self,i,v): print("setitem {},{}".format(i,v)) return list.__setitem__(self,i,v) l = MyList() l.append(12) l.extend([12]) l.remove(12) print(l) l[:] = [4,5,6] l += [5] print(l)
输出:
modification by append modification by extend modification by remove [12] setitem slice(None, None, None),[4, 5, 6] in place add [4, 5, 6, 5]
如你所见
我可能错过了一些通道,但这似乎离我很近。你知道吗
您需要分别重写每个方法。特别是您提到的操作本质上是不同的-append、insert、extend和+=在+创建新列表时就地修改列表。你知道吗
如果你觉得很新奇,这是一种不用写太多样板的潜在方法:
class MyList(list): pass for method in ['append', 'insert', 'extend', '__add__', '__iadd__']: def code_added(self, *args, **kwargs): # Your code here getattr(super(MyList, self), method)(*args, **kwargs) setattr(MyList, method, code_added)
根据要运行的代码访问的内容,可能需要分别处理__add__。你知道吗
正如obskyr的答案所建议的,您必须定义一个子类
list
,重写许多方法,并仔细测试以确定是否遗漏了某些内容。你知道吗我的方法使用更深层次的钩子,使用
__getattribute__
(用于方法调用)、__iadd__
(用于+=
)和__setitem__
(用于切片分配)来捕获最大的更改,并调用原始父方法,使其像一般的中间人一样工作:输出:
如你所见
我可能错过了一些通道,但这似乎离我很近。你知道吗
您需要分别重写每个方法。特别是您提到的操作本质上是不同的-
append
、insert
、extend
和+=
在+
创建新列表时就地修改列表。你知道吗如果你觉得很新奇,这是一种不用写太多样板的潜在方法:
根据要运行的代码访问的内容,可能需要分别处理
__add__
。你知道吗相关问题 更多 >
编程相关推荐