什么是 Python 命名空间

问题描述

我刚刚开始学习 Python &在 Python 中遇到过 "namespaces" 概念.虽然我知道它是什么,但我无法理解这个概念的严重性.

I have just started learning Python & have come across "namespaces" concept in Python. While I got the jist of what it is, but am unable to appreciate the gravity of this concept.

网上的一些浏览显示,反对 PHP 的原因之一是它不支持命名空间.

Some browsing on the net revealed that one of the reasons going against PHP is that it has no native support for namespaces.

有人能解释一下如何使用命名空间吗?此功能如何使编程变得更好(不仅仅是在 Python 中,因为我假设命名空间不是仅限于特定语言的概念).

Could someone explain how to use namespaces & how this feature makes programming better (not just in Python, as I assume namespaces in not a concept limited to a particular language).

我主要来自 Java 和 C 编程背景.

I am predominantly coming from Java and C programming backgrounds.


解决方案

命名空间是实现作用域的一种方式.

Namespace is a way to implement scope.

在 Java(或 C)中,编译器通过静态范围分析确定变量在何处可见.

In Java (or C) the compiler determines where a variable is visible through static scope analysis.

  • 在 C 中,作用域要么是函数体,要么是全局的,要么是外部的.编译器会为您解释这一点,并根据范围规则解析每个变量名称.编译所有模块后,外部名称由链接器解析.

  • In C, scope is either the body of a function or it's global or it's external. The compiler reasons this out for you and resolves each variable name based on scope rules. External names are resolved by the linker after all the modules are compiled.

在 Java 中,作用域是方法函数的主体,或类的所有方法.一些类名也具有模块级范围.同样,编译器会在编译时计算出这一点,并根据作用域规则解析每个名称.

In Java, scope is the body of a method function, or all the methods of a class. Some class names have a module-level scope, also. Again, the compiler figures this out at compile time and resolves each name based on the scope rules.

在 Python 中,每个包、模块、类、函数和方法函数都拥有一个命名空间",在其中解析变量名.另外,如果名称不在本地命名空间中,则使用全局命名空间.

In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. Plus there's a global namespace that's used if the name isn't in the local namespace.

每个变量名在本地命名空间(函数体、模块等)中检查,然后在全局命名空间中检查.

Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global namespace.

变量通常只在本地命名空间中创建.globalnonlocal 语句可以在本地命名空间之外创建变量.

Variables are generally created only in a local namespace. The global and nonlocal statements can create variables in other than the local namespace.

当一个函数、方法函数、模块或包被评估(即开始执行)时,一个命名空间被创建.将其视为评估上下文".当一个函数或方法函数等完成执行时,命名空间被删除.变量被删除.对象也可能被丢弃.

When a function, method function, module or package is evaluated (that is, starts execution) a namespace is created. Think of it as an "evaluation context". When a function or method function, etc., finishes execution, the namespace is dropped. The variables are dropped. The objects may be dropped, also.

相关文章