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:
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
#zoo()
#xy()
def connect(self):
print("class in connect global val:",val)
if 5 == val:
print("global val is:",val)
if __name__=="__main__":
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:
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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.