In this chapter, we will discuss the changes of global variables between modules in Python and other methods for accessing global variables.
1. Modification of global variables between modules
x=1# global variables, is actually the module inside all functions can use Def test (): print (x) if __name__== ' __main__ ': Test ()
The above code is saved as test.py
Import testif __name__== ' __main__ ': test.x=2 test.test () print (test.x)
The above code is saved as test2.py
We run test2.py
Output:
Although the above code implements the modification of global variables between modules, we do not recommend this approach because there are a lot of changes in large applications, and if this cross-module modification is cumbersome for future maintenance
2. Other ways to access global variables
x=1# global variables, in fact, all the functions inside the module can use Def test1 (): x=6 print (' test1: ' +str (x)) def test2 (): Global x x+=1 Print (' Test2: ' +str (x)) def test3 (): import test test.x+=1 print (' Test3: ' +str (test.x)) def test4 (): Import sys module=sys.modules [' Test '] module.x+=1 print (' test4: ' +str (module.x)) if __name__== ' __ Main__ ': test1 () test2 () test3 () test4 () print (x)
The above code is saved as test.py
Run output:
From the above results can be seen, although the others have changed, but the final x is only because the use of the global that sentence to guess the change, the other to no change
Summary: This chapter briefly introduces the modification of global variables between modules and other methods for accessing global variables.
This chapter is here, thank you.
------------------------------------------------------------------
Click to jump 0 basic python-Catalogue
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
0 Basic python-16.5 The modification of global variables between modules and other methods of accessing global variables