cod*_*Joe 6 python global-variables
我有一个全局变量,我将其用作默认变量.根据我的程序中发生的情况,我需要能够更改这些默认值,并通过我的代码的剩余操作保持更改.我希望它们在任何地方都有变化和定义,因此我使用了全局变量 这是一些测试代码,显示了我如何修改这些变量.
当我这样做时,我有以下问题......
myGlobal尚未定义为main.但它有.为什么? myGlobal.我不希望这发生.完成我想要做的事情的正确方法是什么?例子?
#!/usr/bin/python
import sys
myGlobal = "foo"
print "********************"
print "MyGlobal %s" % myGlobal
print "********************"
def main(argv):
#UnboundLocalError: local variable 'myGlobal' referenced before assignment
print '1. Printing the global again: ' + myGlobal
myGlobal = "bar"
print "2. Change the global and print again: " + myGlobal
# now call a subroutine
mySub()
# Checks for output file, if it doesn't exist creates one
def mySub():
# Why isn't the global "bar" not "foo"?
print '3. Printing the global again: ' + myGlobal
myGlobal = "black sheep"
print "4. Change the global and print again: " + myGlobal
if __name__ == "__main__":
main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)
如果要分配给,而不是从函数中读取模块全局变量,则需要global关键字:
def main(argv):
global myGlobal
#...
myGlobal = "bar"
Run Code Online (Sandbox Code Playgroud)
否则,赋值将只创建一个新的局部变量来隐藏全局变量(因此对它的更改不会影响全局变量,就像您的示例中的情况一样).
也就是说,你也可以在这里使用一个类让你的函数以更好的方式共享状态:
class MyApp(object):
def main(self, argv):
self.myVar = "bar"
self.mySub()
def mySub(self):
print self.myVar
MyApp().main(sys.argv[1:])
Run Code Online (Sandbox Code Playgroud)