简体   繁体   English

在python中更改全局变量值的问题

[英]Issues changing a global variable value in python

Suppose I have this function 假设我有这个功能

>>>a=3
>>>def num(a):
       a=5
       return a
>>>num(a)
5
>>>a
3

Value of a doesnt change. 不变的价值。

Now consider this code : 现在考虑这段代码:

>>> index = [1]
>>> def change(a):
       a.append(2)
       return a
>>> change(index)
>>> index
>>> [1,2] 

In this code the value of index changes. 在此代码中,索引的值会发生变化。 Could somebody please explain what is happening in these two codes. 有人可以解释这两个代码中发生的事情。 As per first code, the value of index shouldnt change(ie should remain index=[1]). 根据第一个代码,索引的值不应该改变(即应该保持索引= [1])。

You need to understand how python names work. 您需要了解python名称的工作原理。 There is a good explanation here , and you can click here for an animation of your case. 这是一个很好的解释在这里 ,您可以点击这里为你的情况的动画。

If you actually want to operate on a separate list in your function, you need to make a new one, for instance by using 如果您确实想要在函数中的单独列表上操作,则需要创建一个新列表,例如使用

a = a[:]

before anything else. 在别的之前。 Note that this will only make a new list, but the elements will still be the same. 请注意,这只会生成一个新列表,但元素仍然是相同的。

The value of index doesn't change. index的值不会改变。 index still points to the same object it did before. index仍然指向它之前所做的相同对象。 However, the state of the object index points to has changed. 但是,对象index的状态指向已更改。 That's just how mutable state works. 这就是可变状态的运作方式。

第一个代码块中的第3行是赋值 ,第二个块中的第3行是变异 ,这就是您观察该行为的原因。

The issue you are encountering is: 您遇到的问题是:

a = 3
def num(a):
    # `a` is a reference to the argument passed, here 3.
    a = 5
    # Changed the reference to point at 5, and return the reference.
    return a

num(a)

The a in the num function is a diffrent object than the a defined globally. anum函数比一个不同势对象a全局定义。 It works in case of the list because a points at the list passed, and you modify the object being referenced to by the variable, not the reference variable itself. 它适用于列表,因为列表中a点已通过,并且您修改了变量引用的对象,而不是引用变量本身。

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

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