Python namespace 学习

名称空间,存放名字的地方,准确的说名称空间是存放名字与变量值绑定关系的地方

代码块

代码块语法遵循标准markdown代码,例如:

@ namespace test
def scope_test():
    def do_local():
        spam = "local spam"

    def do_nonlocal():
        nonlocal spam
        spam = "nonlocal spam"

    def do_global():
        global spam
        spam = "global spam"

    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()
    print("After global assignment:", spam)
    # reassign the nonlocal namespace spam
    spam="reassigned nonlocal spam"
    print("After reassignment:", spam)
print(spam)

在console 调用scope_test 函数,得到如下结果

Before calling any enclosing function: test spam
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
After reassignment: reassigned nonlocal spam

scope_test有三个spam,分别是do_local嵌套函数里的局部spam, do_nonlocal嵌套函数里的非局部spam,和do_global嵌套函数里的全局spam,全局spam和scope_test是一个级别的。
1. 在scope_test函数里,首先给非局部spam赋值spam=”test spam”。
2. 接着调用了do_local函数,由于do_local函数里的spam仅仅作用于do_local函数内部,并不能改变scope_test级别的非局部spam,因此调用do_local函数后在scope_test级别打印spam,结果任然是”test spam”。
3. 接着调用do_nonlocal,改变了非局部spam的值,此时打印spam的值结果为”nonlocal spam”
4. 调用do_global函数,do_global函数里定义了一个module级别的全局变量spam,并将它与值“global spam”绑定。这个操作是module级别的,因此在scope_test函数内部打印spam, 打印的任然是非局部spam非全局spam。结果仍然为”nonlocal spam”
5. 在scope函数里给非局部spam重新绑定值,并将值打印,结果为新绑定的值“reassigned nonlocal spam”
6. 最后,在module级别打印spam,打印的将是全局spam,其值为”global spam”

你可能感兴趣的:(Python namespace 学习)