如何在Python中的多个函数之间共享变量,即全局?

时间:2016-01-26 23:00:49

标签: python function global

在下面的代码中,我有两个功能:func1gillespie。我在p_tot_stoch内将func1定义为全局变量。 (将其置于函数内的原因是允许Numba的@jit包装器正常工作...... Numba用于代码优化。)

但是当我尝试在代码的最后打印p_tot_stoch时,我收到以下错误消息:

Traceback (most recent call last):
  File "C:/Users/dis_YO_boi/Documents/Programming/Python/CodeReview.py", line 85, in <module>
    p_tot_stoch = gillespie()
NameError: global name 'p_tot_stoch' is not defined

我将其声明为全局,但看起来主函数gillespie无法访问它。我怎样才能解决这个问题?

我的代码如下,感谢您的帮助。

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from numba import jit
import math
random = np.random

DELTA = 1e-3
SIM_NUM = 100
K_MINUS = 1e-3
K_CAT = 1 - 1e-3
ZETA = 1e-4
D = 10000
QP_VEC = np.logspace(-2, 1, 101, 10)
KAPPA_M = (K_CAT + K_MINUS) / ZETA
P0_VEC = QP_VEC / DELTA
QP_DEG = np.true_divide(1000*D*QP_VEC*K_CAT,1000*QP_VEC+KAPPA_M)

@jit
def func1():
    global p_tot_stoch
    p_tot_stoch = np.empty((SIM_NUM, len(QP_VEC)))

@jit
def gillespie(max_time=1000):
    for len_qp_ind in range(len(QP_VEC)):
        qp = QP_VEC[len_qp_ind]
        p0 = math.ceil(P0_VEC[len_qp_ind])
        for sim_num_ind in range(SIM_NUM):
            p = p0
            d = D
            dp = time = 0

            while True:
                tot = [qp, ZETA * p * d, K_MINUS * dp, K_CAT * dp]
                for i in range(3):
                    tot[i + 1] += tot[i]
                p_tot = p + dp
                kt = tot[-1]
                time += -np.log(1 - random.random()) / kt
                if time > max_time:
                    p_tot_stoch[sim_num_ind, len_qp_ind] = p_tot
                    break

                event_kt = random.random() * kt
                if event_kt < tot[0]:
                    p += 1
                elif event_kt < tot[1]:
                    p -= 1
                    dp += 1
                    d -= 1
                elif event_kt < tot[2]:
                    p += 1
                    dp -= 1
                    d += 1
                elif event_kt < tot[3]:
                    dp -= 1
                    d += 1
    return p_tot_stoch

if __name__ == '__main__':
        p_tot_stoch = gillespie()
        p_mean = p_tot_stoch.mean(axis=0)
        p_std = p_tot_stoch.std(axis=0)
        print(p_tot_stoch)

2 个答案:

答案 0 :(得分:1)

cat test.py

my_variable = 0


def func1():
    global my_variable
    my_variable = -1
    print "func1:{0}".format(my_variable)


def gillespie():
    global my_variable
    my_variable = 4
    print "gillespie:{0}".format(my_variable)


# Starts testing... 
print "before:{0}".format(my_variable)
func1()
gillespie()
print "after:{0}".format(my_variable)

python test.py

before:0
func1:-1
gillespie:4
after:4

你可以在你的顶部声明你的变量p_tot_stoch(在我的test.py中我声明了一个名为my_varialble的变量,它在func1()gillespie()中使用)脚本和您的功能之外。每次要修改它时,都必须声明它是global变量,然后为其分配一个新值。

我正在使用python2.7

答案 1 :(得分:0)

我修改了@ haifzhan的例子,因为它很简单。 Python极大地受益于OOP,不使用它是一种罪过:

#!/usr/bin/env python3

class Stoch:
    def __init__(self):
        self.my_variable = 0

    def __str__(self):
        return str(self.my_variable)

    def func1(self):
        self.my_variable = -1
        print ("func1:", self)

    def gillespie(self):
        self.my_variable = 4
        print ("gillespie:", self)

    @classmethod
    def main(cls):
        stoch = Stoch()
        print ("before:", stoch)    
        stoch.func1()
        stoch.gillespie()
        print ("after:", stoch)

if __name__ == '__main__':
    Stoch.main()