为什么python dict.update()不返回对象? [英] Why doesn't a python dict.update() return the object?

查看:92
本文介绍了为什么python dict.update()不返回对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试:

award_dict = {
    "url" : "http://facebook.com",
    "imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png",
    "count" : 1,
}

def award(name, count, points, desc_string, my_size, parent) :
    if my_size > count :
        a = {
            "name" : name,
            "description" : desc_string % count,
            "points" : points,
            "parent_award" : parent,
        }
        a.update(award_dict)
        return self.add_award(a, siteAlias, alias).award

但是如果在功能上确实很麻烦,我宁愿这样做:

But if felt really cumbersome in the function, and I would have rather done :

        return self.add_award({
            "name" : name,
            "description" : desc_string % count,
            "points" : points,
            "parent_award" : parent,
        }.update(award_dict), siteAlias, alias).award

为什么不更新返回对象,以便您可以链接?

Why doesn't update return the object so you can chain?

JQuery这样做是为了进行链接.为什么在python中不可接受?

JQuery does this to do chaining. Why isn't it acceptable in python?

推荐答案

Python大多实现了

Python's mostly implementing a pragmatically tinged flavor of command-query separation: mutators return None (with pragmatically induced exceptions such as pop;-) so they can't possibly be confused with accessors (and in the same vein, assignment is not an expression, the statement-expression separation is there, and so forth).

这并不意味着没有很多方法可以在您真正想要的时候合并事物,例如,dict(a, **award_dict)做出了一个新的字典,就像您希望.update返回的字典一样-那么为什么如果您真的认为它很重要,可以不使用它?

That doesn't mean there aren't a lot of ways to merge things up when you really want, e.g., dict(a, **award_dict) makes a new dict much like the one you appear to wish .update returned -- so why not use THAT if you really feel it's important?

编辑:顺便说一句,在您的特定情况下,无需按照以下方式创建a:

Edit: btw, no need, in your specific case, to create a along the way, either:

dict(name=name, description=desc % count, points=points, parent_award=parent,
     **award_dict)

创建一个与您的a.update(award_dict)语义完全相同的字典(包括在发生冲突的情况下,award_dict中的条目会覆盖您明确给出的内容;以获取其他语义,即具有赢得"此类冲突的显式条目,将award_dict作为唯一的 positioning arg,传递 before 关键字,并丧失**形式-等).

creates a single dict with exactly the same semantics as your a.update(award_dict) (including, in case of conflicts, the fact that entries in award_dict override those you're giving explicitly; to get the other semantics, i.e., to have explicit entries "winning" such conflicts, pass award_dict as the sole positional arg, before the keyword ones, and bereft of the ** form -- dict(award_dict, name=name etc etc).

这篇关于为什么python dict.update()不返回对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆