問題描述
我剛剛開始學(xué)習(xí) Python &在 Python 中遇到過 "namespaces" 概念.雖然我知道它是什么,但我無法理解這個(gè)概念的嚴(yán)重性.
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.
網(wǎng)上的一些瀏覽顯示,反對(duì) 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 中,因?yàn)槲壹僭O(shè)命名空間不是僅限于特定語言的概念).
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.
推薦答案
命名空間是實(shí)現(xiàn)作用域的一種方式.
Namespace is a way to implement scope.
在 Java(或 C)中,編譯器通過靜態(tài)范圍分析確定變量在何處可見.
In Java (or C) the compiler determines where a variable is visible through static scope analysis.
在 C 中,作用域要么是函數(shù)體,要么是全局的,要么是外部的.編譯器會(huì)為您解釋這一點(diǎn),并根據(jù)范圍規(guī)則解析每個(gè)變量名稱.編譯所有模塊后,外部名稱由鏈接器解析.
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 中,作用域是方法函數(shù)的主體,或類的所有方法.一些類名也具有模塊級(jí)范圍.同樣,編譯器會(huì)在編譯時(shí)計(jì)算出這一點(diǎn),并根據(jù)作用域規(guī)則解析每個(gè)名稱.
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 中,每個(gè)包、模塊、類、函數(shù)和方法函數(shù)都擁有一個(gè)命名空間",在其中解析變量名.另外,如果名稱不在本地命名空間中,則使用全局命名空間.
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.
每個(gè)變量名在本地命名空間(函數(shù)體、模塊等)中檢查,然后在全局命名空間中檢查.
Each variable name is checked in the local namespace (the body of the function, the module, etc.), and then checked in the global namespace.
變量通常只在本地命名空間中創(chuàng)建.global
和 nonlocal
語句可以在本地命名空間之外創(chuàng)建變量.
Variables are generally created only in a local namespace. The global
and nonlocal
statements can create variables in other than the local namespace.
當(dāng)一個(gè)函數(shù)、方法函數(shù)、模塊或包被評(píng)估(即開始執(zhí)行)時(shí),一個(gè)命名空間被創(chuàng)建.將其視為評(píng)估上下文".當(dāng)一個(gè)函數(shù)或方法函數(shù)等完成執(zhí)行時(shí),命名空間被刪除.變量被刪除.對(duì)象也可能被丟棄.
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.
這篇關(guān)于什么是 Python 命名空間的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!