3

我有以下字典:

class Only5Items(dict):
    def __setitem__(self, key, value):
        if len(self) < 5:
            super(Only5Items, self).__setitem__(key, value)

如果我成功添加项目,我想返回 true。有任何想法吗?

我再解释一下。例如:

items = Only5Items()
items["hi1"] = "asdf1"
items["hi2"] = "asdf2"
items["hi3"] = "asdf3"
items["hi4"] = "asdf4"
items["hi5"] = "asdf5"
items["hi6"] = "asdf6"

items["hi6"] = "asdf6"不会插入。我想打印一条关于它的消息。

编辑: len(self) 有效。更具体地说,我不想打印有关它的消息,如果我成功添加它,我想返回真/假。课外的东西。

4

3 回答 3

4

赋值在 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 时,传入最大数量会很好(而且很容易)。

于 2013-10-30T15:41:54.913 回答
2

呃,我只是做以下事情:

class Only5Items(dict):
    def __setitem__(self, key, value):
        if len(self) < 5:
            return super(Only5Items, self).__setitem__(key, value)
        else:
            raise KeyError("You forgot I can only have 5 items dummy!")

    def __str__(self):
        return super(Only5Items, self).__str__()

以下脚本:

d = Only5Items(a=1, b=2, c=3, d=4, e=5)
print d

try:
    d['making a mistake'] = 'hahahahah'
except KeyError, e:
    print e

产生:

{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
'You forgot I can only have 5 items dummy!'
于 2013-10-30T15:42:55.213 回答
1
class Only5Items(dict):
    def __setitem__(self, key, value):
        if len(self) < 5:
            super(Only5Items, self).__setitem__(key, value)
            print "Succesfully inserted!"
        else:
            print "Dictionary full!" 
于 2013-10-30T15:33:06.560 回答