Python 命名空间是什么?

发布于 2024-09-27 01:46:47 字数 264 浏览 1 评论 0原文

我刚刚开始学习 Python 和在 Python 中遇到过“命名空间” 概念。虽然我了解了它的要点,但无法理解这个概念的严重性。

网上的一些浏览显示,PHP 不受欢迎的原因之一是它没有对命名空间的原生支持。

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

我主要有 Java 和 C 编程背景。

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.

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

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).

I am predominantly coming from Java and C programming backgrounds.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

情域 2024-10-04 01:46:47

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

在 Java(或 C)中,编译器通过静态作用域分析确定变量在何处可见。

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

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

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

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

变量通常仅在本地命名空间中创建。 globalnonlocal 语句可以在本地命名空间以外的地方创建变量。

当函数、方法函数、模块或包被求值(即开始执行)时,就会创建一个命名空间。将其视为“评估上下文”。当函数或方法函数等完成执行时,名称空间将被删除。变量被丢弃。物体也可能会掉落。

Namespace is a way to implement scope.

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

  • 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.

  • 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.

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.

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.

甜心小果奶 2024-10-04 01:46:47

要理解命名空间,您还必须对 Python 中的模块有一定的了解。模块只是一个包含 Python 代码的文件。该代码可以是 Python 类、函数或只是名称列表的形式。每个模块都有自己的全局命名空间。因此,同一模块中不能有两个具有相同名称的类或两个函数,因为它们共享模块的名称空间。

参考: http://bytebaker.com/2008/07/30/python-namespaces/

To understand namespaces, you also have to have some understanding of modules in Python. A module is simply a file containing Python code. This code can be in the form of Python classes, functions, or just a list of names. Each module gets it’s own global namespaces. So you can’t have two classes or two functions in the same module with the same name as they share the namespace of the module.

reference: http://bytebaker.com/2008/07/30/python-namespaces/

嗼ふ静 2024-10-04 01:46:47

命名空间可防止不同人编写的同名类、方法和对象之间发生冲突。

来自 Java 背景的您可能熟悉如何使用包来实现这一点,例如您可以创建一个 movieyoda.DateUtils 类,我可以创建一个 mikej.DateUtils 类和包允许代码使用类来区分它们。 (Python 有非常相似的东西。)

命名空间在 5.3.0 中被添加到 PHP 中但在早期版本中(以及在不提供名称空间的其他语言中),您必须在类和方法名称前添加一些前缀,以减少名称冲突的风险。例如,movieyoda_parse_file 函数。

Namespaces prevent conflicts between classes, methods and objects with the same name that might have been written by different people.

Coming from a Java background you are probably familiar with how this is achieved using packages e.g. you might create a movieyoda.DateUtils class and I can create a mikej.DateUtils class and the package allows code using the classes to distinguish between them. (Python has something very similar.)

Namespaces were added to PHP in 5.3.0 but in earlier versions (and in other languages that don't provide namespaces) you would have to prefix your class and method names with something to reduce the risk of a name clash. e.g. a movieyoda_parse_file function.

殤城〤 2024-10-04 01:46:47

命名空间提供了一种管理范围内定义的标识符的方法。换句话说,它们用于将名称映射到值(或更准确地说是对内存位置的引用)。

例如,在命名空间的上下文中,以下表达式

x = 10

会将标识符 x 与保存值为 10 的对象的内存位置相关联。


在 Python 中,本质上有两种“类型”的命名空间; 实例和类命名空间

实例命名空间管理单个对象范围内名称和值之间的映射。另一方面,源代码中定义的每个类都有一个单独的类命名空间。这种类型的命名空间处理由对象的所有实例共享的所有成员。


示例

现在考虑以下示例,其中每个成员都表示它是否属于类或实例命名空间:

class Customer:

    def __init__(self, first_name, last_name, email): # __init__ -> Customer Class Namespace
        self._first_name = first_name # _first_name -> Instance Namespace
        self._last_name = last_name # _last_name -> Instance Namespace
        self._email = email # _email -> Instance Namespace

    def get_full_name(self): # Customer Class Namespace
        return f"{self._first_name} {self._last_name}"


class PremiumCustomer(Customer):

    PREMIUM_MEMBERSHIP_COST = 4.99  # PremiumCustomer Class Namespace


    class Subscription: # PremiumCustomer Class Namespace

        def __init__(self, customer_email): # Subscription Class Namespace
            self._customer_email = customer_email # Instance Namespace

    def __init__(self, first_name, last_name, email, card_number): # PremiumCustomer Class Namespace
        super().__init__(first_name, last_name, email)
        self._card_number = card_number # _card_number -> Instance Namespace

    def get_card_number(self): # PremiumCustomer Class Namespace
        return self._card_number

Namespaces provide a way for managing identifiers defined within a scope. In other words, they are used to map names to values (or references to the memory location to be more precise).

For example, in the context of a namespace the following expression

x = 10

will associate identifier x to the memory location that holds object with value 10.


In Python, there are essentially two "types" of namespaces; instance and class namespaces.

Instance Namespace manages the mapping between names and values within the scope of a individual object. On the other hand, there is a separate Class Namespace for every class defined in the source code. This type of namespace handles all the members which are shared by all instances of the object.


Example

Now consider the following example where for each member it is denoted whether it belongs to a class or instance namespace:

class Customer:

    def __init__(self, first_name, last_name, email): # __init__ -> Customer Class Namespace
        self._first_name = first_name # _first_name -> Instance Namespace
        self._last_name = last_name # _last_name -> Instance Namespace
        self._email = email # _email -> Instance Namespace

    def get_full_name(self): # Customer Class Namespace
        return f"{self._first_name} {self._last_name}"


class PremiumCustomer(Customer):

    PREMIUM_MEMBERSHIP_COST = 4.99  # PremiumCustomer Class Namespace


    class Subscription: # PremiumCustomer Class Namespace

        def __init__(self, customer_email): # Subscription Class Namespace
            self._customer_email = customer_email # Instance Namespace

    def __init__(self, first_name, last_name, email, card_number): # PremiumCustomer Class Namespace
        super().__init__(first_name, last_name, email)
        self._card_number = card_number # _card_number -> Instance Namespace

    def get_card_number(self): # PremiumCustomer Class Namespace
        return self._card_number
も星光 2024-10-04 01:46:47

我完成了 S.Lott 的回答。

我想说,命名空间是在作用域内实现名称管理的一种方法,因为作用域的作用不仅仅是名称管理。

在 C 中,作用域有 4 种类型:全局、函数、块和函数参数(原型)。其中每一种都可以根据需要创建一个或多个命名空间。 C 中有 4 ns
-- s/u/e 标签
-- 类型名、函数名和变量名的 id
-- 函数原型中的参数
-- s/u 内的成员和位域。

像这样,标签标识符和函数名称不会冲突,但 typedef 定义的类型名称可以与变量名称冲突。

在Python中,有一个内置的命名空间包含全局ns,全局ns由加载的模块提供。内置 ns 包含变量。变量的符号可以定义对象或函数——例如,+ 就在那里定义。模块的全局 ns 持续到终止。

另请参阅那个,当然还有那个

I complete the answer of S.Lott.

I would say, namespace is a way to implement name management inside a scope, because a scope does more than name management.

In C the scopes are of 4 types: global, function, block and function-parameters(prototype). Each of these kinds can create one or more namespaces, depending on the needs. There are 4 ns in C
-- tags for s/u/e
-- ids for typenames, function names and var names
-- parameters inside function prototype
-- members and bitfields inside s/u.

Like that, tag identifiers and function names do not collide, but typenames defined by typedef can collide with variable names.

In python there is a builtin namespace that encloses the global ns, and the global ns is provided by the loaded module. The builtin ns contain variables. A symbol for a variable can define an object or a function -- for example, + is defined there. The module's global ns lasts up to the termination.

See also that and of course that.

东风软 2024-10-04 01:46:47

如果你和别人一起编写一个大程序,你可以根据需要编写你自己的程序部分。文件中的所有变量都是私有的,不会有冲突。
当你编写PHP程序时,很容易错误地重写全局变量。在 python 中,如果需要,您可以导入其他模块变量,它们在您的模块上将是“全局”的。

在 Python 中,你可以认为一个文件就是一个对象。当您编写 PHP 程序时,您可以通过编写带有实例变量的类来实现相同的目的。

If you make a big program with someone else, you could write your own part of the program as you want. All variables in the file will be private, there will be no collisions.
When you write PHP programs, it is easy to rewrite global variables by mistake. In python you can import other modules variables if you want, and they will be "global" on your module.

You could think one file one object in Python. When you write PHP programs you can achieve the same by writing classes with instance variables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文