通过继承 collections.UserDict 来实现自己的dict类,通过重写一些特殊方法来定制自己的dict的功能
import collections
class StrKeyDict(collections.UserDict):
"""
A customized class inherted fron UserDict,
get value by converting int type of key to str.
E.g..
mydict = StrKeyDict({'1':'one'})
mydict[1]
output: 'one'
"""
def __missing__(self, key):
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def __contains__(self, key):
return str(key) in self.data
def __setitem__(self, key, item):
self.data[str(key)] = item
if __name__ == '__main__':
mydict = StrKeyDict((('1','one'),('2','two')))
print(mydict[1])
print(1 in mydict)
mydict[3] = 'three'
print(mydict)
这个字典类实现了,通过int类型键取不到值时,将键转换为str类型取值。同时也包括, set 和 in的操作,有相应的功能。
源自于流畅的python