Python,字典复制和更新不起作用?

mgo*_*ser 2 python dictionary copy

为什么以下代码显示None为b,而不是{'a':1,'e':2}?Python 2.7.3

>>>> d = {'a' :1 }
>>>> b = d.copy().update({'e':2})
>>>> print b
None
>>>> d.update({'c':3})
>>>> print d
{'a': 1, 'c': 3}
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 5

dict.update修改dict但返回None.这就是为什么

b = d.copy().update({'e':2})
Run Code Online (Sandbox Code Playgroud)

设置b为相等None,而

d.update({'c':3})
Run Code Online (Sandbox Code Playgroud)

修改d.

许多Python方法都以这种方式运行.例如,list.sort并且random.shuffle还修改一个对象,并返回None.我认为Python这样做是为了阻止长期的"Demeter-scmeter-scoffing"引用链,因为它们不会提高可读性并且可以更难以找到异常.