如何“完美”覆盖一个字典?我怎样才能使“完美”成为dict的子类?最终目标是有一个简单的字典,其中键是小写的。似乎应该有一些微小的原语我可以覆盖以使这项工作,但根据我的所有研究和尝试,似乎情况并非如此:如果我覆盖__getitem__/__setitem__,则get/ set不起作用。我怎样才能让他们工作?当然我不需要单独实施它们?我是否阻止酸洗工作,我是否需要实施__setstate__等?我是否需要repr,update以及__init__?我应该只使用mutablemapping(似乎不应该使用UserDict 或DictMixin)?如果是这样,怎么样?文档并不完全具有启发性。这是我的第一次尝试,get()不起作用,毫无疑问还有许多其他小问题:class arbitrary_dict(dict):
"""A dictionary that applies an arbitrary key-altering function
before accessing the keys."""
def __keytransform__(self, key):
return key # Overridden methods. List from
# https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
# Note: I'm using dict directly, since super(dict, self) doesn't work.
# I'm not sure why, perhaps dict is not a new-style class.
def __getitem__(self, key):
return dict.__getitem__(self, self.__keytransform__(key))
def __setitem__(self, key, value):
return dict.__setitem__(self, self.__keytransform__(key), value)
def __delitem__(self, key):
return dict.__delitem__(self, self.__keytransform__(key))
def __contains__(self, key):
return dict.__contains__(self, self.__keytransform__(key))class lcdict(arbitrary_dict):
def __keytransform__(self, key):
return str(key).lower()
添加回答
举报
0/150
提交
取消