摘自Dive Info Python :http://www.faqs.org/docs/diveintopython/dialect_locals.html
非常奇怪的是,我下的中文版好像没有此章节
4.5. locals and globals
Python has two built-in functions, locals and globals, which provide dictionary-based access to local and global variables.
First, a word on namespaces. This is dry stuff, but it’s important, so pay attention. Python uses what are called namespaces to keep track of variables. A namespace is just like a dictionary where the keys are names of variables and the dictionary values are the values of those variables. In fact, you can access a namespace as a Python dictionary, as we’ll see in a minute.
At any particular point in a Python program, there are several namespaces available. Each function has its own namespace, called the local namespace, which keeps track of the function’s variables, including function arguments and locally defined variables. Each module has its own namespace, called the global namespace, which keeps track of the module’s variables, including functions, classes, any other imported modules, and module-level variables and constants. And there is the built-in namespace, accessible from any module, which holds built-in functions and exceptions.
When a line of code asks for the value of a variable x, Python will search for that variable in all the available namespaces, in order:
- local namespace - specific to the current function or class method. If the function defines a local variable x, or has an argument x, Python will use this and stop searching.
- global namespace - specific to the current module. If the module has defined a variable, function, or class called x, Python will use that and stop searching.
- built-in namespace - global to all modules. As a last resort, Python will assume that x is the name of built-in function or variable.
There is one other important difference between locals and globals, which you should learn now before it bites you. It will bite you anyway, but at least then you’ll remember learning it.