Period of time without using python to write code, I found a lot of previous learning grammar forget. It seems the original aspects of the project to do good enough, there is no systematic use and learning, leading to a lot of grammar can not facile. In this next project,
Some python knowledge unfamiliar places there are sure to encounter forgotten to re-comb, on python to achieve flexibility in the use of state, can not simply be able to knock code to achieve learn, do, teach the three-in-one. That is, learning by doing, learning to do, do teach, teach in secondary schools
realm.
The scope of global variables:
In vitro function generally be a global variable defined variables, variables inside a function defined is referred to as local variables. Global variables are available all scopes, local variables can be used in this function, order of use is variable, local variable> global variable, that is to say: the priority use of local variables
global keyword:
In order to solve the problem using global variables within a function, python increased global keyword, use its features, you can specify the scope of variables.
The role of global keyword: var variable declaration is global
Example one: the assignment function can not change the value of the global variables:
1 global val 2 val = 10 3 4 def test1(): 5 global val 6 val = 5 7 print('test1 global val:',val) 8 9 def test2(): 10 val = 8 11 print('test2 global val:',val) 12 class Test(): 13 def __init__(self): 14 #global val 15 val = 5 16 #zoo() 17 #xy() 18 def connect(self): 19 print("class in connect global val:",val) 20 if 5 == val: 21 print("global val is:",val) 22 23 if __name__=="__main__": 24 Test().connect()
operation result:
class in connect global val: 10
It can be seen in the function assignment does not change the value of a global variable, we need global keyword
Example Two: global variable value change must be global Keywords:
Shen Fu
global val val = 10 def test1(): global val val = 5 print('test1 global val:',val) def test2(): val = 8 print('test2 global val:',val) class Test(): def __init__(self): #global val val = 5 test1() test2() def connect(self): print("class in connect global val:",val) if 5 == val: print("global val is:",val) if __name__=="__main__": Test().connect()
Test Results:
test1 global val: 5
test2 global val: 8
class in connect global val: 5
global val is: 5
As can be seen, changes in the value of a global variable, there must be global keyword. Otherwise it is treated as a local variable. This is sure to write well.