python創造一個新的元類,用於給現有的類增加相應的方法

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的方法,通過寫一個元類,就很容易實現。

 

參考文章:

https://blog.csdn.net/qq_16688265/article/details/80378255

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章