如何在python中定义全局数组
如何在python中定义全局数组 我想将tm和prs定义为全局数组,并在两个函数中使用它们,如何定义它们如何在python中定义全局数组,python,arrays,plot,Python,Arrays,Plot,如何在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-') 您需要
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-')
您需要在方法中将它们称为
global
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-')
阅读有关global
和
global语句是一个声明,用于保存整个当前代码块。这意味着列出的标识符将被解释为全局标识符。如果没有全局变量,就不可能分配给全局变量,尽管自由变量可能引用全局变量而不声明为全局变量
在Python中,仅在函数内部引用的变量是隐式全局变量。如果在函数体中的任何位置为变量指定了新值,则假定该变量为局部变量。如果在函数中为变量分配了一个新值,则该变量是隐式局部变量,您需要显式地将其声明为“全局”
使用关键字:
此外,如果保持当前状态,则无需在第二个函数中将
tm
和prs
声明为全局。只有第一个函数需要它,因为它正在修改全局列表。如果在其他函数中有函数,请使用以下命令:
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
更多信息:您也可以尝试导入
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!必须补充的是,如果要为变量指定新值,则只需要使用global
前缀。如果您只想读取该值,可以使用其常规名称。@TylerAndFriends:“更改值”不如“指定新值”清晰。谢谢!但是很奇怪的是,我可以得到tm和prs的数组,它们都有相同数量的元素,当我使用plt.plot(tm,prs,'k-')时,它返回错误:_tkinter.TclError:没有显示名称和$display环境变量会有帮助吗?
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