9.2.1. 作用域和命名空间示例

这个例子演示了如何引用不同作用域和名称空间,以及 globalnonlocal 会如何影响变量绑定:

  1. def scope_test():
  2. def do_local():
  3. spam = "local spam"
  4. def do_nonlocal():
  5. nonlocal spam
  6. spam = "nonlocal spam"
  7. def do_global():
  8. global spam
  9. spam = "global spam"
  10. spam = "test spam"
  11. do_local()
  12. print("After local assignment:", spam)
  13. do_nonlocal()
  14. print("After nonlocal assignment:", spam)
  15. do_global()
  16. print("After global assignment:", spam)
  17. scope_test()
  18. print("In global scope:", spam)

示例代码的输出是:

  1. After local assignment: test spam
  2. After nonlocal assignment: nonlocal spam
  3. After global assignment: nonlocal spam
  4. In global scope: global spam

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

您还可以在 global 赋值之前看到之前没有 spam 的绑定。