Monday, September 12, 2011

prog: namespace

http://www.freenetpages.co.uk/hp/alan.gauld/tutname.htm

What is namespace?
The concept is pretty straightforward, a namespace is a space or region, within a program, where a name (variable, class etc) is valid. 


We actually use this idea in everyday life. Suppose you work in a big company and there is a colleague called Joe. In the accounts department there is another guy called Joe who you see occasionally but not often. In that case you refer to your colleague as "Joe" and the other one as "Joe in Accounts". You also have a colleague called Susan and there is another Susan in Engineering with whom you work closely. When referring to them you might say "Our Susan" or "Susan from Engineering". Do you see how you use the department name as a qualifier? That's what namespaces do in a program, they tell both programmers and the translator which of several identical names is being referred to.



##### module first.py #########
spam = 42
def print42(): print spam
###############################
##### module second.py ########
from first import *  # import all names from first

spam = 101   # create spam variable, hiding first's version
print42()    # what gets printed? 42 or 101?

################################
If you thought it would print 101 then you were wrong. A name is simply a label used to reference an object. Now in the first module the name print42 refers to the function object defined in the module. So although we imported the name into our module we did not actually import the function which still refers to its own version of spam. Thus when we created our new spam variable it has no effect on the function referred to by print42.






No comments:

Post a Comment