私はデフォルト変数として使用しているグローバル変数を持っています。私のプログラムで何が起こるかに応じて、これらのデフォルトを変更し、コードの残りの操作を通して変更を持続させる必要があります。私はそれらを変更してどこでも定義したいので、グローバル変数を使用しました。これらの変数をどのように変更しようとしているかを示すテストコードをいくつか示します。Pythonでのグローバル変数の混乱
私はこれを行うと、私は次のような問題を持っている...
- プログラムは
myGlobal
がメインで定義されていないと思います。しかし、それは です。どうして? 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:])