我有简单的装饰器,用于在尝试检索 dict 值时替换无效字符。
import types
class ContentInterface(dict):
def __getitem__(self, item):
raise NotImplementedError
class Content(ContentInterface):
def __getitem__(self, item):
return dict.__getitem__(self, item)
class DictDecorator(ContentInterface):
def __init__(self, interfaceContent, **config):
super(DictDecorator, self).__init__()
self._component = interfaceContent
self._config = config
def _replace(self, text):
return text
def _check(self, invalidCharacterSet, itemPath):
pass
def __getitem__(self, name):
item = self._component[name]
if isinstance(item, types.StringTypes):
newText = self._replace(item)
invalidCharacterSet = set([char for char in item if char not in newText])
self._check(invalidCharacterSet, name)
return newText
else:
return self.__class__(item, **self._config)
class ReplaceCommaDecorator(DictDecorator):
def _replace(self, text):
return text.replace(",", ' ')
class ReplaceDotDecorator(DictDecorator):
def _replace(self, text):
return text.replace('.', ' ')
class ReplaceColonDecorator(DictDecorator):
def _replace(self, text):
return text.replace(":", ' ')
class ReplaceSemicolonDecorator(DictDecorator):
def _replace(self, text):
return text.replace(";", ' ')
我想通过以下方式使用它:
dictWithReplacedCharacters =\
ReplaceCommaDecorator( # Empty
ReplaceDotDecorator( # Empty
ReplaceColonDecorator( # Empty
ReplaceSemicolonDecorator( # Empty
Content({ # Data
'1':u'1A:B;C,D.E',
'2':{
'21':u'21A:B;C,D.E',
'22':u'22A:B;C,D.E',
}
}),
),
),
),
)
print dictWithReplacedCharacters['2']['21']
我有 4 个冗余 dict 对象代表一个数据字典的装饰器。
我想强制上面的嵌套语句返回 ReplaceCommaDecorator 对象继承自 ReplaceDotDecorator 继承自 ReplaceColonDecorator 继承自 ReplaceSemicolonDecorator 继承自包含数据的内容。我想这可以在 DictDecorator 的 __new__ 方法中解决。