Python - 命名空间和作用域

Posted Rocinante

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python - 命名空间和作用域相关的知识,希望对你有一定的参考价值。

1. 命名空间和作用域参考

  1. https://blog.csdn.net/sakurainluojia/article/details/72783752
  2. https://docs.python.org/3.6/tutorial/classes.html

概念

A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.

即可以在静态的作用域(本质是一段文本)中访问动态的命名空间(解释器启动时创建)

2. 作用域

  1. https://github.com/jackfrued/Python-100-Days/blob/master/Day01-15/Day06/函数和模块的使用.md

Python查找一个变量时会按照“局部作用域”、“嵌套作用域”、“全局作用域”和“内置作用域”的顺序进行搜索,前三者我们在上面的代码中已经看到了,所谓的“内置作用域”就是Python内置的那些隐含标识符min、len等都属于内置作用域)。
global关键字来指示foo函数中的变量a来自于全局作用域。
nonlocal关键字来指示变量来自于嵌套作用域(enclosing)。

local(局部作用域) -->enclosing(函数范围作用域)-->global(全局作用域)--->build-in(内建对象作用域)

以上是关于Python - 命名空间和作用域的主要内容,如果未能解决你的问题,请参考以下文章

Python命名空间和作用域

Python3 命名空间和作用域

python进阶之命名空间与作用域

Python_命名空间和作用域_25

Python的命名空间和作用域

Python 作用域和命名空间