class DistinctError(BaseException):
def __str__(self):
return "字典中存在重复值,引发这个错误!"
class MyDict(dict):
def __setitem__(self, key, value):
if value in self.values():
if key not in self:
raise DistinctError()
super(MyDict,self).__setitem__(key,value)
d=MyDict()
d['one']='python'
d['two']='python'
print(d)
- 重载[],要求输入不存在的键值时不会报错,而是返回我们自定义的内容
class MyDict(dict):
def __init__(self, default):
self.default = default
super(MyDict,self).__init__()
def __getitem__(self, key):
if key not in self.keys():
return self.default
return super(MyDict,self).__getitem__(key)
d=MyDict('no')
d['one']='python'
d['two']='go'
print(d)
print(d['fish'])