Python中的命名空间和作用域
在Python中,我们处理变量、函数、库和模块等。你可能想要使用的变量名可能已经存在,例如另一个变量名、另一个函数名或另一个方法名。在这种情况下,我们需要了解Python程序如何管理所有这些名称。这就是命名空间的概念。
以下是三种命名空间类别:
局部命名空间:程序声明的所有函数和变量的名称都保存在此命名空间中。此命名空间在程序运行期间存在。
全局命名空间:此命名空间包含Python程序中使用的模块中包含的所有函数和其他变量的名称。它包含局部命名空间中的所有名称。
内置命名空间:这是最高级别的命名空间,其中包含Python解释器加载为编程环境时可用的默认名称。它包含全局命名空间,而全局命名空间又包含局部命名空间。
Python中的作用域
命名空间有一个可用时间,这也被称为作用域。作用域还取决于变量或对象所在的代码区域。在下面的程序中,你可以看到在内循环中声明的变量可用于外循环,反之则不行。还要注意外函数的名称如何也成为全局变量的一部分。
示例
prog_var = 'Hello' def outer_func(): outer_var = 'x' def inner_func(): inner_var = 'y' print(dir(), ' Local Variable in Inner function') inner_func() print(dir(), 'Local variables in outer function') outer_func() print(dir(), 'Global variables ')
运行上述代码将给出以下结果:
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
['inner_var'] Local Variable in Inner function ['inner_func', 'outer_var'] Local variables in outer function ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'outer_func', 'prog_var'] Global variables
广告