Customize built-in

UserDict

from collections import UserDict
class LowerDict(UserDict):
    def __setitem__(self, key, value):
        key = key.lower()
        super().__setitem__(key, value)


ordinals = LowerDict({"FIRST": 1, "SECOND": 2})
ordinals["THIRD"] = 3
ordinals.update({"FOURTH": 4})

ordinals
{'first': 1, 'second': 2, 'third': 3, 'fourth': 4}

isinstance(ordinals, dict)  #False
from collections.abc import MutableMapping

class MyDict(MutableMapping):
    def __init__(self, **kwargs):
        self.data = kwargs

    def __getitem__(self, key):
        return self.data[key]

    def __delitem__(self, key):
        del self.data[key]

    def __setitem__(self, key, value):
        self.data[key] = value

    def __iter__(self):
        return iter(self.data)

    def __len__(self):
        return len(self.data)

    def __repr__(self):
        return repr(self.data)


my_dict = MyDict(a=1, b=2)
my_dict.update(c=3)
my_dict['d'] = 4
my_dict.pop('b')

my_dict   #  {'a': 1, 'c': 3, 'd': 4}

# UserDict 将整个数据结构及方法都默认实现了
# 要改哪个行为,直接覆写对应的方法就好了,很方便。
class MyDict(UserDict):
    def __setitem__(self, key, value):
        super().__setitem__(key, value * 10)


my_dict = MyDict(a=1, b=2)
my_dict   #{'a': 10, 'b': 20}

Last updated