from collections import OrderedDict def pop_by_index(self,i): count=0 for key in self.keys(): if count==i: mykey=key count+=1 self.pop(mykey,None) class DelIndexDict(type): def __new__(cls,name,bases,attrs): attrs['pop_by_index'] = pop_by_index return type.__new__(cls,name,bases,attrs) class DelDict(OrderedDict,metaclass=DelIndexDict): pass
如代码所示,我想要给有序的字典增加一个按照index删除key和value的方法,通过写一个元类,就很容易实现。