如何在python中定义全局数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19139201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define a global array in python
提问by lbjx
How to define a global array in python I want to define tm and prs as global array, and use them in two functions, how could I define them?
如何在python中定义全局数组我想将tm和prs定义为全局数组,并在两个函数中使用它们,我该如何定义它们?
import numpy as np
import matplotlib.pyplot as plt
tm = []
prs = []
def drw_prs_tm(msg):
tm = np.append(tm,t)
prs = np.append(prs,s)
def print_end(msg):
plt.plot(tm,prs,'k-')
采纳答案by karthikr
You need to refer them as global <var_name>
in the method
您需要global <var_name>
在方法中引用它们
def drw_prs_tm(msg):
global tm
global prs
tm = np.append(tm,t)
prs = np.append(prs,s)
def print_end(msg):
global tm
global prs
plt.plot(tm,prs,'k-')
Read more on global
hereand here
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function's body, it's assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global'.
global 语句是适用于整个当前代码块的声明。这意味着列出的标识符将被解释为全局变量。没有全局变量是不可能分配给全局变量的,尽管自由变量可以在没有被声明为全局的情况下引用全局变量。
在 Python 中,仅在函数内部引用的变量是隐式全局变量。如果在函数体内的任何地方为变量分配了新值,则假定它是局部变量。如果一个变量在函数内被赋予了一个新值,则该变量是隐式局部变量,您需要将其显式声明为“全局”。
回答by karthikr
With the global
keyword:
使用global
关键字:
def drw_prs_tm(msg):
global tm, prs # Make tm and prs global
tm = np.append(tm,t)
prs = np.append(prs,s)
Also, if you keep it as it currently is, then you do not need to declare tm
and prs
as global in the second function. Only the first requires it because it is modifying the global lists.
此外,如果您保持当前状态,则无需在第二个函数中将tm
and声明prs
为 global。只有第一个需要它,因为它正在修改全局列表。
回答by Deivydas Voroneckis
In case you have function inside of other function use this:
如果您在其他函数中有函数,请使用以下命令:
def ex8():
ex8.var = 'foo'
def inner():
ex8.var = 'bar'
print 'inside inner, ex8.var is ', ex8.var
inner()
print 'inside outer function, ex8.var is ', ex8.var
ex8()
inside inner, ex8.var is bar
inside outer function, ex8.var is bar
More: http://www.saltycrane.com/blog/2008/01/python-variable-scope-notes/
更多:http: //www.saltycrane.com/blog/2008/01/python-variable-scope-notes/