Namespace and scope

Namespace and scope

First, the name space

1.1 built-in namespace

python interpreter exclusive

eg:

len([1, 2, 3])
int('10')

Function calls have to define, has never been defined. Python interpreter starts up automatically when the python to open up space for a built-in name of these built-in python, python interpreter after stopping explanation will destroy

1.2 global name space

In addition to the built-in local, others are global and

eg:

z = 10   #全局名称空间
def f1():
    x = 10
    def f2():
        y = 10
        print('from f2')

Global needs its own definition, it may have a global name space after the python file is executed, after the end of the file will be destroyed

1.3 The local name space

Variable names defined in the function / function names are stored in the local name space

eg:

z = 10
def f1():
    x = 10   #局部名称空间
    def f2():
        y = 10  #局部名称空间
        print('from f2')

Local also needs its own definition, will have to be generated after the function call, it will be destroyed after the call

Key:

The execution order of three kinds of namespaces: Built-in -> Global -> Local

Find the order of three kinds of namespaces: Start with your current location -> Local -> Global -> Built-in

eg:

x = 1  #全局
def f1():
    x = 3  #局部
f1()
print(x)

Second, the scope (range of an effect)

eg:

x = 1
def f1():
    x = 3
print(x)
# 这里面的x =1和x=3不是同一个东西

2.1 global scope

+ Built-in global variable name space variables, global in scope can only be used in the big picture

x = 1   #x = 1这个变量只能在全局中使用,不能再局部使用,也不能和混着使用
def f1():
    x = 3
print(x)

2.2 local scope

The local name space variables, variables local scope can only be used locally in

eg:

x = 1   # 全局变量
def f1():
    return x
    # print(x)  # f1中的局部
def f2():
    x = 2  # x=2只能在f2中使用
    f1()
f2()  # f1中的局部和f2中的局部互不干涉

Scope function relationships in the definition phase have been identified dead

Third, the understanding of knowledge

3.1 global

eg:

x = 1
def f1():
    global x  # 声明x为全局的x
    x = 3
f1()
print(x)

3.2 nonlocal

def f1():
    x = 1
    def f2():
        nonlocal x  # 针对嵌套函数局部之间的修改
        x = 3
    f2()
    print(x)
f1()

3.3 recommended

eg:

lt = [1,2,3]  # 作用域关系仅适用不可变数据类型,不适用于可变数据类型
def f1():
    lt.append(4)
f1()
print(lt)

Guess you like

Origin www.cnblogs.com/yanjiayi098-001/p/11329355.html