简体   繁体   English

如何在python中定义全局数组

[英]How to define a global array in python

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-')

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 here and here 此处此处阅读有关global更多信息

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. 在Python中,仅在函数内部引用的变量是隐式全局的。 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”。

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. 另外,如果您保持当前状态,则无需在第二个函数中将tmprs声明为全局变量。 Only the first requires it because it is modifying the global lists. 只有第一个需要它,因为它正在修改全局列表。

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/

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

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