链式作业如何工作? [英] How do chained assignments work?

查看:38
本文介绍了链式作业如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

引用某事:

<预><代码>>>>x = y = 某个函数()

相同<预><代码>>>>y = 某个函数()>>>x = y

问题:是

x = y = somefunction()

相同

x = somefunction()y = 某个函数()

?

根据我的理解,它们应该是一样的,因为 somefunction 只能返回一个值.

解决方案

如果 somefunction 返回可变值,它们的工作方式不一定相同.考虑:

<预><代码>>>>def somefunction():... 返回 []...>>>x = y = 某个函数()>>>x.append(4)>>>X[4]>>>是[4]>>>x = 某个函数();y = 某个函数()>>>x.append(3)>>>X[3]>>>是[]

A quote from something:

>>> x = y = somefunction()

is the same as

>>> y = somefunction()
>>> x = y

Question: Is

x = y = somefunction()

the same as

x = somefunction()
y = somefunction()

?

Based on my understanding, they should be same because somefunction can only return exactly one value.

解决方案

They will not necessarily work the same if somefunction returns a mutable value. Consider:

>>> def somefunction():
...     return []
... 
>>> x = y = somefunction()
>>> x.append(4)
>>> x
[4]
>>> y
[4]
>>> x = somefunction(); y = somefunction()
>>> x.append(3)
>>> x
[3]
>>> y
[]

这篇关于链式作业如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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