Python更新全局变量 [英] Python Updating Global variables

查看:96
本文介绍了Python更新全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我我在代码中做错了什么.为什么无法更新我的全局变量?据我了解,如果它是一个全局变量,我可以在任何地方对其进行修改.

Could anyone tell me what I am doing wrong in my code. How come, I cannot update my global variable? To my understanding, if it is a global variable I can modify it anywhere.

如果numpy正在创建新数组(当我使用np.delete时),那么删除numpy数组中的元素的最佳方法是什么.

If the numpy is creating a new array (when I use np.delete), what would be the best way to delete an element in an numpy array.

import numpy as np

global a
a = np.array(['a','b','c','D'])
def hello():
    a = np.delete(a, 1)
    print a

hello()

推荐答案

如果要在函数中使用全局变量,则必须说它是全局变量,在该函数中:

If you want to use a global variable in a function, you have to say it's global IN THAT FUNCTION:

import numpy as np

a = np.array(['a','b','c','D'])
def hello():
    global a
    a = np.delete(a, 1)
    print a

hello()

如果您不使用函数中的global a行,则会创建一个新的局部变量a.因此,关键字global并不是用来创建全局变量的,而是避免创建一个隐藏"已经存在的全局变量的局部变量.

If you wouldn't use the line global a in your function, a new, local variable a would be created. So the keyword global isn't used to create global variable, but to avoid creating a local one that 'hides' an already existing global variable.

这篇关于Python更新全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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