d 我建议你利用全球发言,保持全球范围的这一变量。
关键词global允许你提及全球名称空间的一个变数,尽管在职能呼吁者上存在另一个名称相同的变量。
例如,这将印刷“实质”
def foo():
def bar():
return fruit
fruit = "tangerine"
return bar2()
fruit = "banana"
print(foo()) # will print "tangerine"
但这将印刷“香蕉”。
def foo2():
def bar2():
global fruit # fetch me the fruit in the global scope
return fruit
fruit = "tangerine"
return bar2()
fruit = "banana"
print(foo2()) # will print "banana"
如果没有全球关键词,口译人员将遵循“LEGB规则”,以便找到你再次试图提到的变量:
- L ocal Scope: first, it ll search for the variable in the local scope, the scope in which your function statements are being executed. Local scopes are created everytime a function is called.
- E nclosing Scopes: secondly, the interpreter will look for the variable in the "enclosing function locals", that is the functions in which your function is inserted (declared). That s where the fruit variable is found on the return fruit statement inside bar().
- G lobal: if the variable was not found on the namespaces above, python will try to find it among the global variables. The usage of the global statement forces python to look for it only on the global scope, thus skipping 1 and 2.
- B uiltins: at last, python will try to find the variable among the built-in functions and constants. No magic here.
If all of the searches above fail to find the variable name, python will raise a NameError Exception:
$ NameError: name fruit is not defined
然后,你可以做:
def choosingFunction():
global option
if option == 0:
doThis()
elif option == 1:
doThat()
elif option == 2:
doTheOtherOne()
else:
doWhateverYouFeelLike()
>> option = 2
>> import choosingModule
>> choosingModule.choosingFunction()
铭记依赖模块中存在一个称为你的全球变量,被认为是一种非常坏的做法,并且用吨数来形容任何严重的做法。
For more information on the global statement, check the documentation: Python 3.x and Python 2.7.
And for info about the scopes and namespaces rules check here (Python 3.x) or here (Python 2.7).