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

2024-06-26 13:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我有两个函数:func1和{}。我已经将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

我将其声明为global,但看起来主函数gillespie无法访问它。我该怎么解决这个问题?在

我的代码在下面,谢谢你的帮助。在

^{pr2}$

Tags: 函数代码定义错误原因globaljit末尾
2条回答

猫测试.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测试.py在

^{pr2}$

您可以声明变量p_tot_stoch(在my测试.py我声明了一个名为my_varialble的变量,它用于脚本顶部和函数外部的func1()和{})。每次你想修改它,你必须声明它是一个global变量,然后给它赋值。在

我用的是python2.7

我修改了@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()

相关问题 更多 >