获取__setitem __()的返回值和字典长度

时间:2013-10-30 15:28:22

标签: python

我有以下字典:

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)有效。更具体地说,我不想打印关于它的消息,如果我成功添加它,我想返回true / false。课堂外的东西。

3 个答案:

答案 0 :(得分:3)

在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。

答案 1 :(得分: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!'

答案 2 :(得分: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!"