Python的一些内部细节

1、关于变量空间
摘自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:

  1. 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.
  2. 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.
  3. 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.

Example 4.12. locals is read-only, globals is not

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值