3 回答

TA贡献1836条经验 获得超13个赞
如果somefunction返回可变值,它们不一定会一样工作。考虑:
>>> def somefunction():
... return []
...
>>> x = y = somefunction()
>>> x.append(4)
>>> x
[4]
>>> y
[4]
>>> x = somefunction(); y = somefunction()
>>> x.append(3)
>>> x
[3]
>>> y
[]

TA贡献1806条经验 获得超5个赞
都不行
x = y = some_function()
相当于
temp = some_function()
x = temp
y = temp
注意订单。最左边的目标被首先分配。(在C语言中类似的表达式可能以相反的顺序分配。)从有关Python分配的文档中:
...将单个结果对象从左到右分配给每个目标列表。
拆卸显示如下:
>>> def chained_assignment():
... x = y = some_function()
...
>>> import dis
>>> dis.dis(chained_assignment)
2 0 LOAD_GLOBAL 0 (some_function)
3 CALL_FUNCTION 0
6 DUP_TOP
7 STORE_FAST 0 (x)
10 STORE_FAST 1 (y)
13 LOAD_CONST 0 (None)
16 RETURN_VALUE
注意:始终将同一对象分配给每个目标。因此,正如@Wilduck和@andronikus指出的那样,您可能永远都不想这样:
x = y = [] # Wrong.
在上述情况下,x和y指代相同的列表。因为列表是可变的,所以追加到x 似乎会影响 y。
x = [] # Right.
y = []
现在,您有两个名称,分别引用了两个不同的空列表。

TA贡献1836条经验 获得超4个赞
仅当函数没有副作用并以确定性方式返回单例(给定其输入)时,结果才会相同。
例如:
def is_computer_on():
return True
x = y = is_computer_on()
要么
def get_that_constant():
return some_immutable_global_constant
请注意,结果将是相同的,但实现结果的过程将不会:
def slow_is_computer_on():
sleep(10)
return True
x和y变量的内容相同,但指令x = y = slow_is_computer_on()将持续10秒,而其对应内容x = slow_is_computer_on() ; y = slow_is_computer_on()将持续20秒。
这将是几乎如果该函数不具有副作用,并返回一个不可变的以确定的方式相同的(给定其输入)。
例如:
def count_three(i):
return (i+1, i+2, i+3)
x = y = count_three(42)
请注意,适用上一节中说明的相同捕获。
为什么我说差不多?因为这:
x = y = count_three(42)
x is y # <- is True
x = count_three(42)
y = count_three(42)
x is y # <- is False
好的,使用is有些奇怪,但这说明返回的结果是不一样的。这对于可变情况很重要:
如果函数返回可变值,则很危险,并可能导致错误
这个问题也得到了回答。为了完整起见,我重播该参数:
def mutable_count_three(i):
return [i+1, i+2, i+3]
x = y = mutable_count_three(i)
因为在那种情况下x,并y是同一个对象,做这样的操作x.append(42)对子级意味着两个x并y持有到现在有4个元素的列表的引用。
如果该功能有副作用,那将是不一样的
考虑到打印的副作用(我认为这是有效的,但也可以使用其他示例):
def is_computer_on_with_side_effect():
print "Hello world, I have been called!"
return True
x = y = is_computer_on_with_side_effect() # One print
# The following are *two* prints:
x = is_computer_on_with_side_effect()
y = is_computer_on_with_side_effect()
它可能会带来更复杂或更微妙的副作用,而不是打印出来,但是事实仍然存在:该方法被调用一次或两次,并且可能导致不同的行为。
如果函数在给定其输入的情况下是不确定的,那就会不同
也许是一个简单的随机方法:
def throw_dice():
# This is a 2d6 throw:
return random.randint(1,6) + random.randint(1,6)
x = y = throw_dice() # x and y will have the same value
# The following may lead to different values:
x = throw_dice()
y = throw_dice()
但是,涉及到时钟,全局计数器,系统的东西,等东西是明智的是非确定性给出的输入,在这些情况下的价值x和y可能发散。
添加回答
举报