Advanced use of Python primary variables, in-depth analysis and explanation ~


foreword

Get an in-depth understanding of the basics of python, and use the most basic knowledge to slap the interviewer.


The scope of variables

1. What is the scope of a variable?

When creating, changing, and looking up variable names in a Python program, they are all done in a space that holds variable names, which we call 命名空间and are also called 作用域.

Python的作用域是静态的, the location in the source code where the variable name is assigned is determined 该变量能被访问的范围. That is, the scope of a Python variable is 所在源代码中的位置determined by the variable.

2. Scope generation

Only when variables are defined in Module (module) , Class (class) , def ( function ), there will be a concept of scope.

Variables defined in a scope are generally only valid in that scope.

In a statement block with keywords such as if-elif-else, for-else, while, etc.try-except / try-finally并不会产生作用域

2.1. Code Analysis

We first define a variable number in the function:

def func():
	number = 100
	print(number)


print(number)

Executing the function we will get an error ERROR: NameError: name 'number' is not defined
insert image description here
The above is the function, we define the code within a condition to define the number:


if True:
    number = 100
    print(number)
print("******输出分隔符******")
print(number)

The result of executing this code:
insert image description here
It can be concluded that
there is scope in our case def函数, but there is no scope in our ifconditional demo.

3. Types of Scope (LEGB Law)

L (local): local scope (namespace inside a function)

E (enclosing) nested scope (namespace for outer nested functions)

G (global) global scope (namespace of the module (file) where it is located)

B (built-in) built-in scope (the namespace of Python's built-in modules)

3.1. Code Analysis

globalVar = 100  # 全局作用域 (既然是全局就代表任何地方可用)


def nest_scope():
    enclosingVar = 200  # 嵌套作用域(可在嵌套函数中使用)

    def func():
        localVar = enclosingVar + 1  # 局部作用域(只能在当前函数func 使用)
        print(localVar)
    return func()


print(__name__)  # 内置作用域

3.2. (LEGB rule) Priority for searching variable names

When an undetermined variable name is used in a function, Python searches four scopes in order of priority to determine the meaning of the variable name.
First search the local scope ( L ),

followed by the nested scope ( E ) of the def or lambda function in the previous nested structure ,

followed by the global scope ( G ),

Finally there is the built-in scope ( B ).

According to this search principle, stop at the first place found. If not found, an NameErrorerror occurs.

3.2.1. The precedence of searching for variable names

局部作用域 > 嵌套作用域 > 全局作用域 > 内置作用域

3.2.2. Code Analysis

|-------------------------------------示例1--------------------------------------|
def func():
    number = 256
    print(number)  # 输出局部作用域的number 
 
 
number = 1024
func()
print(number) # 输出全局作用域的number 

运行结果:
256
1024

|-------------------------------------示例2--------------------------------------|
def nest_scope():
    number = 256
    print(number)

    def func():
        print(number)  # 此处输出的是上层嵌套函数nest_scope()中的number

    func()


number = 1024
nest_scope()
print(number)


运行结果:
256
256 
1024
|-------------------------------------示例3--------------------------------------|
number = 1024
def func():
    print(number)  # 此处的变量number对应的肯定是下一行中所声明的局部变量, 但是未被赋值之前引用了所以会报错
    number = 256


func()
print(number)


运行结果:
UnboundLocalError: local variable 'number' referenced before assignment

|-------------------------------------示例4--------------------------------------|
number = 1024
def func():
    print(number)
    # number = 256  # 此行定义的局部变量被注释掉之后, 上一行所对应的应该是全局变量中的number


func()
print(number)


运行结果:
1024
1024

The above code can clearly draw the conclusion of the priority order of LEGB laws.

Second, the difference between global and nonlocal keywords

1. global is suitable for modifying the value of global variables inside the function

number = 1024


def test_update_number():
    def nested_func():
        global number  # 绑定到了第一行定义的number
        print('current_number=', number)  # 输出当前number的值
        number = 200

    return nested_func()


test_update_number()
print(number)  # 输出修改后的值

输出结果:
current_number= 1024
200

2. nonlocal is suitable for inner functions in nested functions to modify the value of outer variables

def func_outer():
    number = 10

    def func_inner():
        nonlocal number  # 绑定到了第二行定义的number
        print("current_number=", number)  # 未被修改之前的值
        number = 20
        print(number)  # 内层输出修改后的值

    func_inner()
    print(number)  # 外层输出修改后的值


func_outer()

 输出结果:
current_number= 10
20
20

From this, you can see their differences and the correct usage.


Summarize

The sorting of basic knowledge is also very important. It will be used in the daily development process and the interview process. Well, today's sharing is over, and you are welcome to correct me.

Guess you like

Origin blog.csdn.net/Return_Li/article/details/119854896