Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python全局变量在另一个模块中为None_Python_Global Variables - Fatal编程技术网

Python全局变量在另一个模块中为None

Python全局变量在另一个模块中为None,python,global-variables,Python,Global Variables,我对全局变量有这个问题。在我为一个模块中的全局变量显式赋值之后,我尝试从另一个模块访问函数中的这个全局变量。它不包含任何内容,即使已经为其指定了值。下面是我的代码,演示了我的观点: a、 py(主文件) b、 派克 注意:在运行a.py之前,先创建一个名为“file”的文件(无扩展名) 当我运行a.py时,我得到以下输出: Traceback (most recent call last): File "a.py", line 24, in <module> fun(f)

我对全局变量有这个问题。在我为一个模块中的全局变量显式赋值之后,我尝试从另一个模块访问函数中的这个全局变量。它不包含任何内容,即使已经为其指定了值。下面是我的代码,演示了我的观点:

a、 py(主文件)

b、 派克

注意:在运行a.py之前,先创建一个名为“file”的文件(无扩展名)

当我运行a.py时,我得到以下输出:

Traceback (most recent call last):
  File "a.py", line 24, in <module>
    fun(f)
  File "a.py", line 19, in fun
    x.do_shit()
  File "F:\Peep\b.py", line 7, in do_shit
    assert a.fname is not None
AssertionError
回溯(最近一次呼叫最后一次):
文件“a.py”,第24行,在
乐趣(f)
文件“a.py”,第19行,在fun中
x、 拉屎
文件“F:\Peep\b.py”,第7行,在do\u shit中
assert a.fname不是None
断言错误

有人能解释为什么来自另一个模块的全局变量为None,以及我如何解决这个问题吗?提前感谢。

不要重新导入已启动的模块。如果这样做,内存中将有两个版本:一个为
\uuuu main\uuuu
,另一个为
a
。一般来说,使用全局变量是一种非常糟糕的做法,因此我会尝试不同的方法。在任何情况下,当您运行b.py时,a.py的
\uuuu main\uuuu
部分将永远不会运行,因为导入模块时该部分将被忽略
class Foo:
    def __init__(self, thing):
        self.thing = thing

    def do_shit(self):
        import a
        assert a.fname is not None
Traceback (most recent call last):
  File "a.py", line 24, in <module>
    fun(f)
  File "a.py", line 19, in fun
    x.do_shit()
  File "F:\Peep\b.py", line 7, in do_shit
    assert a.fname is not None
AssertionError