简体   繁体   English

说明无法分配给 Function 调用错误

[英]Explain Can't Assign To Function Call Error

def func(lst):
    return lst[0]
 
 lst = [1,2,3]

 func(lst) = 5 #a

 lst[0] = 5 #b

Why does 'a' give me a "can't assign to function call" error and 'b' runs perfectly fine, even though they are saying the same thing.为什么'a'给我一个“不能分配给 function 调用”错误,而'b'运行得很好,即使他们说的是同样的事情。 Please explain and/or provide alternatives to what I am trying to do.请解释和/或提供替代我正在尝试做的事情。 (Ignore faulty indentation) (忽略错误的缩进)

When you do lst[0]=5 you are actually changing the first element of your list lst to 5. Therefore, you can assign the value 5.当您执行lst[0]=5时,您实际上是将列表lst的第一个元素更改为 5。因此,您可以assign值 5。

However, when you do func(lst) for the algorithm, you are trying to give func(lst) a value 5, which is not doable.但是,当您为算法执行func(lst)时,您试图给func(lst)一个值 5,这是不可行的。

However, what you can do is to check if func(lst) == 5 Which means, does the value given by func(lst) equal to 5?但是,您可以做的是检查是否func(lst) == 5这意味着func(lst) equal to 5?

What do you think it "should" mean, if you were allowed to do func(lst) = 5 ?如果允许您执行func(lst) = 5 ,您认为它“应该”是什么意思?

You seem to be fixated by the fact that, in this case, func(lst) happens to always equal lst[0] , and that you know this - but what would it mean if func(lst) where to, say, always return 2 ?您似乎被这样一个事实所吸引,在这种情况下, func(lst)恰好总是等于lst[0] ,并且您知道这一点 - 但是如果func(lst)总是返回,这意味着什么2 ? Would you expect that to mean you could set 2 equal to 5 (or whatever else you assigned)?您是否希望这意味着您可以将2设置为5 (或您分配的任何其他值)? That's clearly nonsensical.这显然是荒谬的。 And what if the function didn't return anything?如果 function 没有返回任何东西怎么办?

The only things you can assign to are variables, and to object properties (of which list indices are a special case).您可以分配的唯一内容是变量和 object 属性(其中列表索引是一种特殊情况)。 A function call returns neither of these, but a value . function 调用既不返回这些,也返回一个 Variables and object properties hold (or contain ) a value, but they are not in themselves values.变量和 object 属性持有(或包含)一个值,但它们本身不是值。 It makes sense to assign to one of these, but you can't assign to a value.分配给其中之一是有意义的,但您不能分配给值。

In particular the lst[0] that your function returns doesn't actually bear any relation to lst itself.特别是您的 function 返回的lst[0]实际上与lst本身没有任何关系。 That's just how your function calculates its value - it looks at the list its been passed and takes the first element.这就是您的 function 计算其值的方式 - 它查看已传递的列表并获取第一个元素。 But once it has done that and found, say, 1 (as in your example), that value of 1 is just 1 - it is "detached" from the list.但是一旦它完成并找到 1 (如您的示例中所示),则 1 的值只是 1 - 它从列表中“分离”。

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

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