在Python中,ABC(抽象基类)是一个提供接口定义和部分实现的类。它们不能直接实例化,而是用作其他类的基类。在ABC集合中,def(_f)和del(_f)分别代表“定义”和“删除”方法。
下面是一个示例代码:
from collections import ABC, MutableMapping
class MyDict(MutableMapping):
# 继承MutableMapping基类
def __init__(self, **kwargs):
self.store = dict()
self.update(kwargs)
def __getitem__(self, key):
return self.store[self._keytransform(key)]
def __setitem__(self, key, value):
self.store[self._keytransform(key)] = value
def __delitem__(self, key):
del self.store[self._keytransform(key)]
def __iter__(self):
return iter(self.store)
def __len__(self):
return len(self.store)
def _keytransform(self, key):
return key
class ReadOnlyMapping(ABC):
# 继承ABC基类
@def(MutableMapping)
def __getitem__(self, key):
return self.store[self._keytransform(key)]
@def(MutableMapping)
def __iter__(self):
return iter(self.store)
@def(MutableMapping)
def __len__(self):
return len(self.store)
@del(MutableMapping)
def __setitem__(self, key, value):
raise NotImplementedError()
@del(MutableMapping)
def __delitem__(self, key):
raise NotImplementedError()
class MyReadOnlyDict(ReadOnlyMapping):
# 继承ReadOnlyMapping基类
def __init__(self, **kwargs):
self.store = dict()
self.update(kwargs)
def __setitem__(self, key, value):
self.store[self._keytransform(key)] = value
def __delitem__(self, key):
del self.store[self._keytransform(key)]
def _keytransform(self, key):
return key.upper()
d = MyDict()
print(d) # {}
d['a'] =
上一篇:abc建站