简体   繁体   English

您可以为返回的对象分配值吗?

[英]Can you assign a value to a returned object?

I am trying to implement Euclid's algorithm in Python3. 我正在尝试在Python3中实现Euclid算法。 If max(a, b) returns the object with the largest value in (a, b), why can't you operate on that object like so: 如果max(a,b)返回(a,b)中具有最大值的对象,为什么不能像这样操作该对象:

max(a, b) %= min(a, b)

>>> a = 5
>>> b = 6
>>> max(a, b) %= min(a, b)
  File "<stdin>", line 1
SyntaxError: can't assign to function call

The interpreter has spoken. 口译员已发言。 You are trying to operate on a value/object, which is not possible. 您试图对一个值/对象进行操作,这是不可能的。 Assignments can be performed on variables only, which are references pointing to said values/objects. 只能对变量进行赋值,变量是指向所述值/对象的引用。

Even if you could do it, it's pointless, because you're trying to change the return value of a function, that hasn't been captured by any variable. 即使您可以做到这一点,也没有意义,因为您正在尝试更改函数的返回值,而该值尚未被任何变量捕获。 You can't even use it. 您甚至无法使用它。

I believe the short answer to your question is no . 我相信您的问题的简短答案是“ 否” The function max(a,b) is returning the largest value to you, not a variable reference to the largest value. 函数max(a,b)向您返回最大值,而不是返回引用最大值的变量。

I believe what you are looking for is: 我相信您正在寻找的是:

if max(a,b) == a:
    a %= min(a,b)
else
    b %= min(a,b)

which will check if the largest value is indeed the variable a before the assignment. 它将在分配前检查最大值是否确实是变量a。

You can only assign to variables, but there's no way for a function to return a variable. 您只能分配给变量,但是函数无法返回变量。 (It can only return a value.) (它只能返回一个值。)

For example: 例如:

a = 4
b = 5
max(a, b)  # What does this return?

max(a, b) returns the value 5 , not the variable b . max(a, b)返回 5 ,而不是变量 b (So the code you're trying to write is essentially 5 = ... which makes little sense.) (因此,您要编写的代码本质上是5 = ... ,这毫无意义。)

You can't do like this, the function max returns a value, not a variable, what you can do, however is to execute: 您不能这样做,函数max返回一个值而不是变量,但是您可以执行以下操作:

a,b = sorted((a,b))

then, after this line, a will always be the greater value (or equal b ) 然后,在此行之后, a将始终是较大的值(或等于b

this way you can just do in the line after: 这样,您可以在之后的一行中执行操作:

a%=b

Since b will be the min value... 由于b将是最小值...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM