Last active
January 14, 2018 06:35
-
-
Save nlpjoe/b6d5fc5f6b54d27bda74eab3d92d81a0 to your computer and use it in GitHub Desktop.
[自定义字典映射类型]非字符串键转字符串#python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import collections | |
class StrKeyDict0(dict): # 继承dict | |
def __missing__(self, key): | |
if isinstance(key, str): # 找不到的键是字符串,抛出keyerror异常 | |
raise KeyError(key) | |
return self[str(key)] # 找不到的键转为字符串再查找 | |
def get(self, key, default=None): | |
try: | |
return self[key] # 调用__getitem__,找不到会调用__missing__方法 | |
except KeyError: | |
return default # 如果抛出KeyError异常,说明__missing__方法也查找失败 | |
def __contains__(self, key): | |
return key in self.keys() or str(key) in self.keys() # 先根据传入键的原本值查找,再转为str键查找 | |
class StrKeyDict(collections.UserDict): # self.data是存储数据的地方 | |
def __missing__(self, key): | |
if isinstance(key, str): | |
raise KeyError(key) | |
else: | |
return self[str(key)] | |
def __setitem__(self, key, item): # 把key都以字符串形式存储,存在self.data中 | |
self.data[str(key)] = item | |
def __contains__(self, key): | |
return str(key) in self.data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment