gpt4 book ai didi

python - Python中跨模块和静态方法访问全局变量

转载 作者:行者123 更新时间:2023-11-30 22:42:52 33 4
gpt4 key购买 nike

假设有两个名为 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) code>) 是一个尝试访问上述全局变量的静态方法。函数 getConcat 访问静态方法,并应该返回一个连接的字符串。

# cat MyModule.py
import GlobVars as GV
class MyClass:
def __init__(self, var1):
self.var1 = var1
@staticmethod
def _concat(var2):
GV.getGlobVars().go()
return var2 + my_glob_var

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

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

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

最佳答案

在您的特定情况下,您不必使用 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

关于python - Python中跨模块和静态方法访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978216/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com