当前位置 : 主页 > 编程语言 > python >

#yyds干货盘点#python类的作用域

来源:互联网 收集:自由互联 发布时间:2022-06-18
如何引用不同作用域和名称空间,以及​​global​​和​​nonlocal​对变量绑定的影响: def scope_test(): def do_local(): spam = "local spam" def do_nonlocal(): nonlocal spam spam = "nonlocal spam" def do_global

如何引用不同作用域和名称空间,以及 ​​global​​ 和 ​​nonlocal​ 对变量绑定的影响:

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)

scope_test()
print("In global scope:", spam)

示例代码的输出是:

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

注意,局部 赋值(这是默认状态)不会改变 ​scope_test​ 对 ​spam​ 的绑定。 nonlocal 赋值会改变 ​scope_test​ 对 ​spam​ 的绑定,而 global 赋值会改变模块层级的绑定。

而且,global 赋值前没有 ​spam​ 的绑定。

网友评论