Reading the following simple Python script, can you tell if the final output is ‘abc’ or ‘def’?
a = "abc"
def f():
print(a)
def main():
a = "def"
f()
if __name__ == "__main__":
main()
The result maybe surprising – it’s ‘abc’. Although the main() method explicitly set the global variable ‘a’ to value ‘def’ before calling the f() method, the value assignment took no effect.
Why? This is because the variable namespace. When you say a = ‘def’ in main() method, Python thinks you’ve declared a new local variable with name ‘a’. So ‘def’ is assigned to this new local variable instead of the global variable. To change the global variable ‘a’, you’ll need to add:
global a
before the assignment. The statement informs Python that the variable ‘a’ referred in the method is indeed a global variable, not a local variable.
0 comments:
Post a Comment