简体   繁体   中英

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?

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

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

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

With the global keyword:

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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