在Python中,跨模块和静态方法访问全局变量的方法

2024-06-24 13:47:59 发布

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

假设两个名为GlobVarsMyModule的Python模块。在

模块GlobVars旨在为另一个模块提供全局变量my_glob_var。在

# cat GlobVars.py
class getGlobVars:
    def __init__(self):
        global my_glob_var
        my_glob_var = 'World'
    def go(self):
        pass

模块MyModule包含一个具有两个函数(_concatgetConcat)的类,其中一个函数(即_concat)是一个尝试访问上述全局变量的静态方法。{static}返回一个连接的函数。在

^{pr2}$

当我试图加载两个模块并执行函数getConcat时,似乎无法正确访问全局变量。为什么会这样?解决办法是什么?在

import MyModule
import GlobVars
print MyModule.MyClass('!').getConcat()
# NameError: global name 'my_glob_var' is not defined

Tags: 模块函数importselfvarmydefglobal
1条回答
网友
1楼 · 发布于 2024-06-24 13:47:59

在您的特定情况下,您不必使用global关键字,也不必使用GlobVars类。

取而代之的是:

# cat GlobVars.py
my_glob_var = 'World'

# cat MyModule.py
import GlobVars as GV
class MyClass:
    def __init__(self, var1):
        self.var1 = var1

    @staticmethod
    def _concat(var2):
        return var2 + GV.my_glob_var

    def getConcat(self):
        return MyClass._concat('Hello ')+self.var1

顺便说一句,python文档很少涉及跨模块共享全局变量:https://docs.python.org/3/faq/programming.html?highlight=global#how-do-i-share-global-variables-across-modules

相关问题 更多 >