http___en.wikipedia.org_wiki_Namespace__programming_.xml
1.1 2.1 2.2 3.1 4.1 5.1 5.2 6.1 7.1 8.1 9.1 10.1 10.2 10.3 11.1 12.1 13.1 13.2 14.1 15.1 16.1 17.1 18.1 19.1 20.1 20.2 20.3 20.4 20.5 21.1 22.1 23.1 24.1 24.2 24.3 24.4 25.1 25.2 26.1 27.1 28.1 29.1 29.2 29.3 29.4 30.1 30.2 30.3 30.4 31.1 31.2 32.1 32.2 33.1 34.1 35.1 36.1 37.1
Именно пространство Именното пространство (на английски: Namespace) представлява контейнер, съдържащ набор от идентификатори(имена), и осигурява пояснение на омонимните идентификатори, които се намират в различни именни пространства. Именните пространства обикновено обединяват имената, базирайки се на функционалността им. Съдържание Система на именуване[редактиране | edit source] Името в едно именно пространство се състои от именен идентификатор и локално име. Обикновено именното пространство се добавя към локалното име като представка. Във следната ABNF(Augmented Backus-Naur Form) форма: name =   separator Примери[редактиране | edit source] Именни пространства в езика C#[редактиране | edit source] Именните пространства са широко използвани в езика C#. Всички класове във средата за програмиране .NET(.NET Framework) са организирани в именни пространства, за да се използват по предназначение, без да настъпи объркване. Освен това, програмистите много често създават собствени именни пространства като по този начин организират по-добре работата си и избягват дублиране на имена.Когато използваме даден клас, той трябва да съдържа и именното пространство, в което се намира, System.Console.WriteLine("Hello World!"); int i = System.Convert.ToInt32("123"); или се добавя using последвано от именното пространство, което се използва, по този начин се избягва пълното изписване на името на класа. using System; . Console.WriteLine("Hello World!"); int i = Convert.ToInt32("123"); В горните примери, System представлява именно пространство, а Console и Convert са класове, намиращи се в него. В следващия пример се вижда елементарно приложение на именно пространство, в което се намират три класа: using System; using WikiArticle; namespace WikiArticle { class First { public void WriteSomething() { Console.WriteLine("Wikipedia"); } } class Second { public void Language() { Console.WriteLine("CSharp"); } } } namespace Performance { class Program { static void Main(string[] args) { First something = new First(); something.WriteSomething(); Second codingLanguage = new Second(); codingLanguage.Language(); } } } Именни пространства в езика C++[редактиране | edit source] В C++ именно пространство се дефинира с именен блок. namespace abc { int bar; } В този блок, идентификаторите се използват точно както са декларирани. Извън него, пространствения спецификатор трябва да бъде използван с представка. Например, извън именното пространство bcd, bar трябва да се изпише bcd::bar, за да се осигури достъп до него. Езикът C++ поддържа друга конструкция, която улеснява програмиста. Чрез добавянето на реда using namespace bcd; към кода, представката bcd:: не е нужна. Код, който не е изрично деклариран в именно пространство, по подразбиране се намира в глобалното именно пространство. Класифицирането по именни пространства в C++ е йерархично. Например, ако разгледаме именното пространство храна::супа, идентификаторът пиле се отнася до храна::супа::пиле. Ако храна::супа::пиле не съществува, тогава се отнася до храна::пиле. Ако нито храна::супа::пиле, нито храна::пиле съществуват, тогава пиле се отнася до ::пиле, идентификатор в глобалното именно пространство. Именните пространства в C++ най-често се използват, за да се избегнат т.нар "сблъсъци" при именуване. въпреки че именните пространства са широко използвани в този език, по-старите програми, които са писани на него, не ползват тази негова функционалност. Например, цялата стандартна библиотека на C++(standard library) е дефинирана във namespace std, но преди стандартизацията много от компонентите ѝ се намират във глобалното именно пространство. Следният пример демонстрира употребата на именни пространства в C++: #include   using namespace std; // first namespace namespace first_space { void functionOne() { cout << "Inside first_space" << endl; } } // second namespace namespace second_space { class Example { public: static void functionTwo() { cout << "Inside second_space" << endl; } }; } int main () { // Calls function from first namespace. first_space::functionOne(); // Calls function from second namespace. second_space::Example::functionTwo(); return 0; } Пакет (package) в езика Java[редактиране | edit source] В Java, идеята за именно пространство е пренесена в пакети(packages). Целият код представлява част от пакет, въпреки че изричното му посочване не е задължително. Достъпът до код от други пакети се осъществява чрез използването на името на пакета като представка пред съответния идентификатор, например класът String в пакета java.lang може да бъде достъпен като: java.lang.String(тази конструкция представлява цялото име на даден клас). Подобно на C++, Java предлага конструкция, която прави ненужно изписването името на пакета. Въпреки това, определени функции( като отражението) изискват от програмиста да използва пълната конструкция при извикването им. За разлика от C++, в Java именните пространства не са подредени йерархично по отношение на синтаксиса на езика. Въпреки това, именуването на пакетите е йерархично. Например, всички пакети започващи с java са част от платформата на езика — пакетът java.lang съдържа основните класове в Java и пакетът java.lang.reflect съдържа основните класове се отнасят конкретно за отражението. В Java(както и Ada, C# и др.), именните пространства/пакетите изразяват семантични категории код. Например, в C# именното пространство System съдържа код, осигурен от .NET Framework. Колко специфични са тези категории и от колко задълбочена йерархия са част, е различно при различните езици. Обхватът на функция или клас може да се разглежда като скрито именно пространство, в което имената са неразривно свързани откъм видимост, достъпност и живот на обекта. В този пример виждаме как се дефинира и използва пакет в Java: Дефинирането се осъществява по следния начин: package animals; interface Animal { public void eat(); public void travel(); } А това е изпълнението(имплементацията): package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println("Mammal eats"); } public void travel() { System.out.println("Mammal travels"); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } }
1.1 2.1 2.2 2.3 3.1 4.1 5.1 6.1 6.2 7.1 8.1 9.1 10.1 11.1 11.2 12.1 13.1 14.1 15.1 16.1 17.1 18.1 19.1 20.1 21.1 22.1 23.1 24.1 24.2 24.3 24.4 25.1 26.1 27.1 27.2 28.1 29.1 30.1 30.2 31.1 32.1 32.2 32.3 33.1 33.2 34.1 35.1 36.1 37.1 38.1 39.1 40.1 41.1 41.2 41.3 41.4 41.5 42.1 42.2 42.3 42.4 42.5 42.6 43.1 43.2 43.3 44.1 44.2 44.3 44.4 44.5 44.6 45.1 47.1 47.2 47.3 49.1 50.1 51.1 51.2 51.3 52.1 53.1 54.1 54.2 54.3 55.1 56.1 57.1 58.1 59.1 59.2 60.1 61.1 62.1 62.2 63.1 64.1 64.2 65.1 66.1 67.1 68.1 69.1 69.2 69.3 70.1 70.2 70.3 71.1 72.1 72.2 72.3 73.1 74.1 75.1 75.2 75.3 76.1 76.2 77.1 77.2 77.3 78.1 79.1 80.1 81.1 81.2 82.1 82.2 83.1 85.1 85.2 85.3 85.4 86.1 86.2 86.3 86.4 87.1 87.2 88.1 88.2 88.3 89.1 90.1 91.1 92.1 93.1 94.1 95.1 96.1 96.2 97.1 98.1 99.1 100.1 100.2 101.1 102.1 102.2 102.3 103.1 104.1 105.1 106.1 107.1 107.2 107.3 108.1 109.1 109.2 110.1 111.1 112.1 113.1 114.1 114.2 115.1 115.2 115.3 116.1 117.1 118.1 119.1 120.1 121.1 122.1 123.1 124.1 125.1 126.1 127.1 128.1 129.1 129.2 130.1 130.2 130.3 131.1 131.2 132.1 133.1 134.1 134.2 135.1 135.2 135.3 135.4 135.5 136.1 136.2 137.1 137.2 137.3 137.4 137.5 138.1 138.2 139.1 139.2 139.3 140.1 140.2 141.1 141.2 142.1 142.2 142.3 142.4 143.1 143.2
Namespace In general, a namespace is a container for a set of identifiers (also known as symbols, names).[1][2] Namespaces provide a level of direction to specific identifiers, thus making it possible to distinguish between identifiers with the same exact name. For example, a surname could be thought of as a namespace that makes it possible to distinguish people who have the same given name. In computer programming, namespaces are typically employed for the purpose of grouping symbols and identifiers around a particular functionality. Contents For Starters[edit] Name conflicts[edit] Element names are defined by the developer. This often results in a conflict when trying to mix XML documents from different XML applications. This XML carries HTML table information: Apples   Bananas This XML carries information about a table (i.e. a piece of furniture): African Coffee Table   80   120 If these XML fragments were added together, there would be a name conflict. Both contain a   element, but the elements have different content and meaning. An XML parser will not know how to handle these differences. Solution via prefix[edit] Name conflicts in XML can easily be avoided using a name prefix. The following XML distinguishes between information about the HTML table and furniture by prefixing "h" and "f" at the beginning of the respective tags:[3] Civil Engineering    Electrical Engineering           A Engineering College    80   120 Naming system[edit] A name in a namespace consists of a namespace identifier and a local name.[4][5] The namespace name is usually applied as a prefix to the local name. In Augmented Backus-Naur Form: name =   separator When local names are used by themselves, name resolution is used to decide which (if any) particular item is alluded to by some particular local name. Examples[edit] Delegation[edit] Delegation of responsibilities between parties is important real-world applications, such as the structure of the World Wide Web. Namespaces allow delegation of identifier assignment to multiple name issuing organisations whilst retaining global uniqueness.[7] A central Registration authority registers the assigned namespace identifiers allocated. Each namespace identifier is allocated to an organisation which is subsequently responsible for the assignment of names in their allocated namespace. This organisation may be a name issuing organisation that assign the names themselves, or another Registration authority which further delegates parts of their namespace to different organisations. Hierarchy[edit] A naming scheme that allows subdelegation of namespaces to third parties is a hierarchical namespace A hierarchy is recursive if the syntax for the namespace identifiers is the same for each subdelegation. An example of a recursive hierarchy is the Domain name system. An example of a non-recursive hierarchy are Uniform resource name representing an Internet Assigned Numbers Authority (ISBN) number. Namespace versus scope[edit] A namespace identifier may provide context (Scope in computer science) to a name, and the terms are sometimes used interchangeably. However, the context of a name may also be provided by other factors, such as the location where it occurs or the syntax of the name. In programming languages[edit] For many programming languages, namespace is a context for their identifiers. In an operating system, an example of namespace is a directory. Each name in a directory uniquely identifies one file or subdirectory, but one file may have the same name multiple times.[8] As a rule, names in a namespace cannot have more than one meaning; that is, different meanings cannot share the same name in the same namespace. A namespace is also called a context, because the same name in different namespaces can have different meanings, each one appropriate for its namespace. Following are other characteristics of namespaces: - Names in the namespace can represent objects as well as concepts, be the namespace a natural or ethnic language, a constructed language, the technical terminology of a profession, a dialect, a sociolect, or an artificial language (e.g., a programming language). - In the Java programming language, identifiers that appear in namespaces have a short (local) name and a unique long "qualified" name for use outside the namespace. - Some compilers (for languages such as C++) combine namespaces and names for internal use in the compiler in a process called name mangling. Below is an example of a namespace in C++: namespace Box1{ int boxSide = 4; } namespace Box2{ int boxSide = 12; } int main () { int boxSide = 42; cout << Box1::boxSide << endl; //output 4 cout << Box2::boxSide << endl; //output 12 cout << boxSide << endl; // output 42 return 0; } Computer science considerations[edit] A namespace in computer science (sometimes also called a name scope), is an abstract container or environment created to hold a logical grouping of unique identifiers or symbols (i.e., names). An identifier defined in a namespace is associated only with that namespace. The same identifier can be independently defined in multiple namespaces. That is, the meaning associated with an identifier defined in one namespace may or may not have the same meaning as the same identifier defined in another namespace. Languages that support namespaces specify the rules that determine to which namespace an identifier (not its definition) belongs.[9] This concept can be illustrated with an analogy. Imagine that two companies, X and Y, each assign ID numbers to their employees. X should not have two employees with the same ID number, and likewise for Y; but it is not a problem for the same ID number to be used at both companies. For example, if Bill works for company X and Jane works for company Y, then it is not a problem for each of them to be employee #123. In this analogy, the ID number is the identifier, and the company serves as the namespace. It does not cause problems for the same identifier to identify a different person in each namespace. In large computer programs or documents it is not uncommon to have hundreds or thousands of identifiers. Namespaces (or a similar technique, see Emulating namespaces) provide a mechanism for hiding local identifiers. They provide a means of grouping logically related identifiers into corresponding namespaces, thereby making the system more modular. Data storage devices and many modern programming languages support namespaces. Storage devices use directories (or folders) as namespaces. This allows two files with the same name to be stored on the device so long as they are stored in different directories. In some programming languages (e.g. C++, Python), the identifiers naming namespaces are themselves associated with an enclosing namespace. Thus, in these languages namespaces can nest, forming a namespace tree. At the root of this tree is the unnamed global namespace. Use in common languages[edit] // // Creating something similar to namespaces in C using structs. #include  int main() { struct jim { //create a structure type jim int a; //jim contains an integer type called a char c; //jim's type of layout also has room for a character called c }betty; //we now created an image of jim called betty betty.a = 1; //betty's a is 1 betty.c = 'j'; //betty's c is j struct jim james; //create another instance of jim and call it 'james' james.a = 2; //james's a is 2 james.c = 'c'; //james's c is c printf("betty.a is %d\n",betty.a); //printing or outputting a in betty will output 1 printf("james.a is %d\n",james.a); //printing or outputting a in james will output 2 //in both printf cases, we address a variable a, but from two different names. //we have basically created namespaces in C. return 0; } In C++, a namespace is defined with a namespace block.[10] namespace abc { int bar; } Within this block, identifiers can be used exactly as they are declared. Outside of this block, the namespace specifier must be prefixed. For example, outside of namespace abc, bar must be written abc::bar to be accessed. C++ includes another construct that makes this verbosity unnecessary. By adding the line using namespace abc; to a piece of code, the prefix abc:: is no longer needed. Code that is not explicitly declared within a namespace is considered to be in the global namespace. Namespace resolution in C++ is hierarchical. This means that within the hypothetical namespace food::soup, the identifier chicken refers to food::soup::chicken. If food::soup::chicken doesn't exist, it then refers to food::chicken. If neither food::soup::chicken nor food::chicken exist, chicken refers to ::chicken, an identifier in the global namespace. Namespaces in C++ are most often used to avoid naming collisions. Although namespaces are used extensively in recent C++ code, most older code does not use this facility. For example, the entire C++ standard library is defined within namespace std, but before standardization many components were originally in the global namespace. However, when namespaces are used, it's considered to be against good code practices. Bjarne Stroustrup, designer of C++, has said himself that using namespaces is unsafe and wished he had not included it in the language. - Java In Java, the idea of a namespace is embodied in Java packages. All code belongs to a package, although that package need not be explicitly named. Code from other packages is accessed by prefixing the package name before the appropriate identifier, for example class String in package java.lang can be referred to as java.lang. String (this is known as the fully qualified class name). Like C++, Java offers a construct that makes it unnecessary to type the package name ( import). However, certain features (such as reflection) require the programmer to use the fully qualified name. Unlike C++, namespaces in Java are not hierarchical as far as the syntax of the language is concerned. However, packages are named in a hierarchical manner. For example, all packages beginning with java are a part of the Java platform—the package java.lang contains classes core to the language, and java.lang.reflect contains core classes specifically relating to reflection. In Java (and Ada, C#, and others), namespaces/packages express semantic categories of code. For example, in C#, namespace System contains code provided by the system (the .NET Framework). How specific these categories are and how deep the hierarchies go differ from language to language. Function and class scopes can be viewed as implicit namespaces that are inextricably linked with visibility, accessibility, and object lifetime. Namespaces are heavily used in C# language. All .NET Framework classes are organized in namespaces, to be used more clearly and to avoid chaos. Furthermore, custom namespaces are extensively used by programmers, both to organize their work and to avoid naming collisions. When referencing a class, one should specify either its fully qualified name, which means namespace followed by the class name, System. Console. WriteLine("Hello World!"); int i = System. Convert. or add a using statement. This, eliminates the need to mention the complete name of all classes in that namespace. using System; . Console. WriteLine("Hello World!"); int i = Convert. In the above examples, System is a namespace, and Console and Convert are classes defined within System. - Python In Python, namespaces are defined by the individual modules, and since modules can be contained in hierarchical packages, then name spaces are hierarchical too.[11][12] In general when a module is imported then the names defined in the module are defined via that module's name space, and are accessed in from the calling modules by using the fully qualified name. # assume modulea defines two functions : func1() and func2() and one class : class1 import modulea modulea.func1() modulea.func2() a = modulea.class1() The "from ... import ..." can be used to insert the relevant names directly into the calling module's namespace, and those names can be accessed from the calling module without the qualified name : # assume modulea defines two functions : func1() and func2() and one class : class1 from modulea import func1 func1() func2() # this will fail as an undefined name, as will the full name modulea.func2() a = class1() # this will fail as an undefined name, as will the full name modulea.class1() Since this directly imports names (without qualification) it can overwrite existing names with no warnings. A special form is "from ... import *", which imports all names defined in the named package directly in the calling modules namespace. Use of this form of import, although supported within the language, is generally discouraged as it pollutes the namespace of the calling module and will cause already defined names to be overwritten in the case of name clashes. Python also supports "import x as y" as a way of providing an alias or alternative name for use by the calling module: import numpy as np a = np.arange(1000) - XML namespace In XML, the XML namespace specification enables the names of elements and attributes in an XML document to be unique, similar to the role of namespaces in programming languages. Using XML namespaces, XML documents may contain element or attribute names from more than one XML vocabulary. - PHP Namespaces were introduced into PHP from version 5.3 onwards. Naming collision of classes, functions and variables can be avoided. In PHP, a namespace is defined with a namespace block. # assume this is a class file defines two functions : foo() and bar() # location of the file phpstar/foobar.php namespace phpstar; class fooBar { public function foo() { echo 'hello world, from function foo'; } public function bar() { echo 'hello world, from function bar'; } } We can reference a PHP namespace with the following different ways: # location of the file index.php # Include the file include "phpstar/foobar.php"; # Option 1: directly prefix the class name with the namespace $obj_foobar = new \phpstar\fooBar(); # Option 2: import the namespace use phpstar\fooBar; $obj_foobar = new fooBar(); # Option 2a: import & alias the namespace use phpstar\fooBar as FB; $obj_foobar = new FB(); # Access the properties and methods with regular way $obj_foobar->foo(); $obj_foobar->bar(); Emulating namespaces[edit] In programming languages lacking language support for namespaces, namespaces can be emulated to some extent by using an identifier naming convention. For example, C libraries such as Libpng often use a fixed prefix for all functions and variables that are part of their exposed interface. Libpng exposes identifiers such as: png_create_write_struct png_get_signature png_read_row png_set_invalid This naming convention provides reasonable assurance that the identifiers are unique and can therefore be used in larger programs without fear of identifier naming collisions. Likewise, many packages originally written in Fortran (e.g., BLAS, LAPACK) reserve the first few letters of a function's name to indicate which group it belongs to. Unfortunately, this technique has several drawbacks: - It doesn't scale well to nested namespaces; identifiers become excessively long. - Individuals or organizations may use dramatically inconsistent naming conventions, potentially introducing unwanted obfuscation. - Compound or 'query-based' operations on groups of identifiers, based on the namespaces in which they are declared, are rendered unwieldy or unfeasible. - All uses of the identifiers must, in effect, be fully namespace-qualified. Languages with direct support for namespaces usually provide ways for the programmer to declare up front that they wish to use some or all identifiers from a specific namespace, which they can then use without qualification for the remainder of the block. - In languages in which identifier length is restricted, the use of prefixes limits the number of characters that can be used to identify what the function does. This is a particular problem for packages originally written in FORTRAN 77, which offered only 6 characters per identifier. For example, the name of the BLAS function DGEMMfunction indicates that it operates on double precision numbers ('D') and general matrices ('GE'), and only the last two characters show what it actually does: matrix-matrix multiplication (the 'MM'). See also[edit] - 11-Digit Delivery point ZIP code - Binomial nomenclature (genus-species in biology) - Chemical nomenclature - Dewey Decimal Classification - Digital object identifier - Domain Name System (DNS) names (Internet addresses) - Identity (object-oriented programming) - Library of Congress Classification - Star catalogues and astronomical naming conventions - XML namespace References[edit] - ^ "C# FAQ: What is a namespace". http://en.csharp-online.net/: C# Online Net. A namespace is nothing but a group of assemblies, classes, or types. A namespace acts as a container—like a disk folder—for classes organized into groups usually based on functionality. C# namespace syntax allows namespaces to be nested. - ^ "namespace". Webopedia. The set of names in a naming system. - ^ Template:Comilla - ^ XML Core Working Group (8 December 2009). "Namespaces in XML 1.0 (Third Edition)". - ^ Moats, Ryan (May 1997). "Syntax". URN Syntax. IETF. https://tools.ietf.org/html/rfc2141#section-2. - ^ Stephen J. Gowdy. "List of USB ID's". - ^ Sollins & Masinter (December 1994). "Requirements for functional capabilities". Functional Requirements for Uniform Resource Names. IETF. https://tools.ietf.org/html/rfc1731#section-2. - ^ "C# FAQ: What is a namespace". http://en.csharp-online.net/: C# Online Net. For instance, [under Windows], to access the built-in input-output (I/O) classes and members, use the System.IO namespace. Or, to access Web-related classes and members, use the System. Web namespace. - ^ "A namespace is "a logical grouping of the names used within a program."". Webopedia.com. - ^ "Namespaces allow to group entities like classes, objects and functions under a name.". Cplusplus.com. Modules". The Python Tutorial. Python Software Foundation. Retrieved 25 October 2010. - ^ "Python Scopes and Namespaces". Docs.python.org.