全局变量不在python中更新 [英] Global variable is not updating in python
问题描述
globalVar.py
全球m_pTest
m_pTest =无
FileOne.py
import globalVar
import fileTwo
m_pTest = Class.getOutput()#Value is assigne
fileTwo.fun( )
#做任何事
fileTwo.py
import globalVar
def fun():
intVal = m_pTest.getInt()#int value from m_pTest object
print intVal
这是我的简短程序示例,当我运行它时,会在fileTwo.py中带来错误, ()
AttributeError:'NoneType'对象没有属性'getInt'
有人可以解释此代码中的错误吗?
谢谢!
全局m_pTest
不会让变量神奇地变成全球性的;相反,它在当前范围中设置名称 m_pTest
来引用全局变量(来自外部范围)。因此,把它放在 globalVar.py
中基本上没有任何东西。
如果你只想导入变量,你可以使用以下内容:
from globalVar import m_pTest
但是,当将 m_pTest
设置为不同的值时,不会影响在 globalVar.py
所以这个改变在其他地方没有看到。
相反,您必须导入 globalVar
,然后参考 m_pTest
作为该模块的成员:
import globalVar
#reading
print(globalVar.m_pTest)
#setting
globalVar.m_pTest = 123
I have 3 files.
globalVar.py
global m_pTest
m_pTest = None
FileOne.py
import globalVar
import fileTwo
m_pTest = Class.getOutput() # Value is assigne
fileTwo.fun()
#Do anything
fileTwo.py
import globalVar
def fun():
intVal = m_pTest.getInt() # int value from m_pTest object
print intVal
This is my short program sample when i run this it gives error in fileTwo.py in fun()
AttributeError: 'NoneType' object has no attribute 'getInt'
Can someone explain what is wrong in this code ? Thank you!
global m_pTest
doesn’t make a variable magically global; instead it sets the name m_pTest
in the current scope to refer to a global variable (from outer scope). So placing it in globalVar.py
does basically nothing.
If you wanted to import only the variable, you could use the following:
from globalVar import m_pTest
However, when setting m_pTest
to a different value, you will not affect the original object that was created in globalVar.py
so the change isn’t seen elsewhere.
Instead, you have to import globalVar
as normal, and then refer to m_pTest
as a member of that module:
import globalVar
# reading
print(globalVar.m_pTest)
# setting
globalVar.m_pTest = 123
这篇关于全局变量不在python中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!