[英]Change global variable across class in python
I am trying to make a change to a global variable across classes. 我正在尝试更改跨类的全局变量。 Here is my code: 这是我的代码:
file main.py 文件main.py
import class2
class first:
def changeA(self):
global a
print a
a += 2
print a
test0 = first()
test1 = class2.second()
test2 = first()
test3 = class2.second()
test0.changeA()
test1.changeA()
test2.changeA()
test3.changeA()
file class2.py 文件class2.py
a = 1
class second:
def changeA(self):
global a
print a
a += 1
print a
But it returns an error: global name 'a' is not defined. 但它返回一个错误:全局名称'a'未定义。 Is there any proper way to access and change a global variable across files in python? 有没有适当的方法来访问和更改python中跨文件的全局变量? Thanks in advance 提前致谢
Global variables don't exist in python. 全局变量在python中不存在。
The global
statement is really a misnomed statement. global
语句实际上是一个错误的语句。 What it means is that the variable is a module 's variable. 这意味着变量是模块的变量。 There is no such a thing as a global namespace in python. python中没有全局名称空间之类的东西。
If you want to modify a variable from multiple modules you must set it as an attribute: 如果要从多个模块修改变量,则必须将其设置为属性:
import module
module.variable = value
Doing a simple assignment will simply create or modify a module's variable. 做一个简单的分配将简单地创建或修改模块的变量。 The code 编码
from module import variable
variable = value
simply shadows the value of variable
imported from module
creating a new binding with that identifier but module
's variable
value will not be changed. 只是隐藏了从module
导入的variable
的值,并使用该标识符创建了一个新的绑定,但是module
的variable
值将不会更改。
In summary: no there is no way to achieve exactly what you want (although what you want would be a bad practice anyway, and you should try to use a different solution). 总结:没有任何方法可以完全实现您想要的(尽管您想要的仍然是一种不好的做法,您应该尝试使用其他解决方案)。
global variables are evil: avoid them! 全局变量是邪恶的:避免使用它们!
It is much better to use a 'static' (in C++ terms) member variable, such as: 最好使用“静态”(用C ++术语)成员变量,例如:
from class2 import second
class first:
def changeA(self):
print second.a
second.a += 2
print second.a
And: 和:
class second:
a = 1
def changeA(self):
print second.a
second.a += 2
print second.a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.