赋值在 Python 中没有返回值,并且 的返回值__setitem__()
被忽略。通常,您希望引发异常:
class Only5Items(dict):
def __setitem__(self, key, value):
if len(self) < 5 or key in self: # allow reassignment of existing key
return super(Only5Items, self).__setitem__(key, value)
raise KeyError("maximum number of items (5) exceeded")
然后您的客户端代码可以捕获异常:
items = Only5Items(hi1="asdf1", hi2="asdf2", hi3="asdf3", hi4="asdf4", hi5="asdf5")
try:
items["hi6"] = "asdf6"
except KeyError as e:
print(e)
如果要返回True/False
,则必须编写自己的可以返回值的赋值方法:
class Only5Items(dict):
def __setitem__(self, key, value):
if len(self) < 5 or key in self: # allow reassignment of existing key
return super(Only5Items, self).__setitem__(key, value)
raise KeyError("maximum number of items (5) exceeded")
def did_set(self, key, value):
try:
self[key] = value
except KeyError:
return False
return True
然后你会像这样使用它:
if not items.did_set("hi6", "asdf6"):
print "couldn't set key 'hi6', dictionary is probably full"
您可能还想重写setdefault()
以检查项目数......另外,当您实例化类而不是将其硬编码为 5 时,传入最大数量会很好(而且很容易)。