程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The global and nonlocal keywords under the scope of Python

編輯:Python

global and nonlocal Scope

This part involves Python Knowledge of variable scope , Variable scope refers to the effective scope of a variable , Direct understanding is Python Variables in are not accessible anywhere , There are restrictions .

In general, the scope of a variable is Block level 、 function 、 class 、 modular 、 Bag, etc , The level is from childhood to .Python There is no block level scope in , So when we write code , The following code is correct .

if True:
x = "hello world"
# Because there is no block level scope , so if Variables in the code block x Can be accessed from outside
print(x)

stay Python Common block level scopes in are if sentence 、for sentence 、while sentence 、with Context statement .

Python Scope in

As mentioned above, the scope is Python A program can directly access the scope of a variable ,Python There are a total of 4 Kind of , They are as follows :

  1. L(Local): The innermost layer , Contains local variables , For example, functions ( Method ) Inside ;
  2. E(Enclosing): Include nonlocal (nonlocal) It's not the whole picture (nonglobal) The variable of , In nested functions , function A Include functions B, stay B China to visit A The variables in the , The scope is nonlocal, To understand it directly is to understand the variables in the function outside the closure function ;
  3. G(Global): The outermost layer of the code , Global variables ;
  4. B(Built-in): Contains built-in variables .

A classic case is as follows :

# Built in scope Built-in
x = int(5/2)
# Global scope Global
global_var = 0
def outer():
# In a function other than a closure function Enclosing
out_var = 1
def inner():
# Local scope Local
inner_var = 2

stay Python The order of finding variables in is from inside to outside , First, local , And then outside , In the global , Built in , This rule is called LEGB The rules .

Make the following study more interesting , You can study how variables change in the following code .

len = len([])
def a():
len = 1
def b():
len = 2
print(len)
b()
a()

global keyword

It's defined in Internal function The variable of has a local scope , It's defined in Function external Variables of have global scope .

Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program .

# Global variables
x = 0
def demo():
# At this time x It's a local variable
x = 123
print(" Function is a local variable x = ", x)
demo()
print(" Outside the function is the global variable x= ", x)

Output results , Inside the function is 123, The outside of the function is still 0.

If you want the function to be internal ( Internal scope ) You can modify variables in an external scope , Need to use global keyword .

# Global variables
x = 0
def demo():
# At this time x Global variable
global x
x = 123
print(" Function is a local variable x = ", x)
demo()
print(" Outside the function is the global variable x= ", x)

At this point, the output is 123 了 , There's one more thing to note , In the function content, if you want to modify the value of the global variable ,global Keywords must be written before variable operations .

def demo():
# At this time x Global variable
x = 123
global x
print(" Function is a local variable x = ", x)

The code has syntax errors :

SyntaxError: name 'x' is assigned to before global declaration

In addition to the above knowledge , Remember to use a variable inside a function , Without changing the value , No statement , By default, the value of global variable is obtained .

x = " Global variables "
def demo():
print(x)
demo()

There is also a real interview question in the global variable , Often appear , May I ask the following code running results .

x = 10
def demo():
x += 1
print(x)
demo()

The conclusion is to report an error , The reason is that demo Function runtime , It will be calculated first. x+1, Variables need to be declared and assigned before they are evaluated , But the inner part of the function is right x No initialization operation , So report a mistake .

nonlocal keyword

If you want to modify the nested scope (Enclosing Scope ) The variables in the , need nonlocal keyword , The test code is as follows :

def outer():
num = 10
def inner():
# nonlocal keyword
nonlocal num
num = 100
print(num)
inner()
print(num)
outer()

The output is self tested , Be careful nonlocal Keyword must be Python3.X+ edition ,Python 2.X There will be syntax errors in the version :

 nonlocal num
^
SyntaxError: invalid syntax`

nonlocal Can not replace global, For example, the following code , Comment out the variable declaration of the outer function , This will bring up SyntaxError: no binding for nonlocal 'num' found error .

num = 10
def outer():
# Comment out the line
# num = 10
def inner():
# nonlocal keyword
nonlocal num
num = 100
print(num)
inner()
print(num)
outer()

In multiple nesting ,nonlocal It only goes up one level , If the upper floor doesn't have , Will continue to go up , You can comment the following code separately to see the result .

num = 10
def outer():
num = 100
def inner():
num = 1000
def inner1():
nonlocal num
num = 10000
print(num)
inner1()
print(num)
inner()
print(num)
outer()

What are the local variables and global variables , Can pass locals() and globals() Two built-in functions get .

x = " Global variables "
def demo():
y = " local variable "
print(locals())
print(x)
demo()
print(globals())
print(locals())

The summary of this blog

This blog explains Python Scope of action , And right global and nonlocal Keywords learned , I hope it helped you .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved