免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2755 | 回复: 0
打印 上一主题 下一主题

Python 3.1.1 中英文对照版语言参考手册 - 执行模型 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-11-29 17:16 |只看该作者 |倒序浏览
4. 执行模型(Execution model)

4.1. 名字与绑定(Naming and binding)

Names refer to objects.  Names are introduced by name binding operations.
Each occurrence of a name in the program text refers to the binding of
that name established in the innermost function block containing the use.
名字( Names )是一个对象的引用。名字是通过名字绑定操作引入的。在程序文本中名字的每次出现,都是引用了在最内层函数块建立的针对所用名字的绑定( binding )。
A block is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block.  A script file (a file given as
standard input to the interpreter or specified on the interpreter command line
the first argument) is a code block.  A script command (a command specified on
the interpreter command line with the ‘-c‘ option) is a code block.  The
string argument passed to the built-in functions
eval()
and
exec()
is a code block.
代码块( block )是可以作为执行单元的一段Python程序代码。以下都属于代码块:模块、函数体和类定义。每条交互式输入的命令都是一个代码块。脚本文件(通过标准输入或者命令行的第一个参数告知解释器)也是代码块。脚本命令(由命令行选项 ‘-c‘ 指定)也是代码块。传递给内置函数
eval()

exec()
的字符串参数也是代码块。
A code block is executed in an execution frame.  A frame contains some
administrative information (used for debugging) and determines where and how
execution continues after the code block’s execution has completed.
代码块是在执行栈桢( execution frame )内执行的。栈桢包括有某些管理性信息(用于调试),并决定了执行完这段代码块后在什么地方、如何继续。
A scope defines the visibility of a name within a block.  If a local
variable is defined in a block, its scope includes that block.  If the
definition occurs in a function block, the scope extends to any blocks contained
within the defining one, unless a contained block introduces a different binding
for the name.  The scope of names defined in a class block is limited to the
class block; it does not extend to the code blocks of methods – this includes
comprehensions and generator expressions since they are implemented using a
function scope.  This means that the following will fail:
作用域( scope
)定义了名字在代码块内的可见性。如果局部变量是在一个代码块内部定义的,那么这个局部变量的作用域包括这个代码块。如果定义出现在一个函数块里,那么定
义域会扩展到这个函数所包括的任何块,除非内部块对这个名字有另外的绑定。在类块中定义的名字绑定限于该类块内,它不会扩展到方法的代码块中--包括
comprehensions和generator表达式,因为这些也是使用函数作用域实现的。这意味着以下代码会失败:
class A:
    a = 42
    b = list(a + i for i in range(10))
When a name is used in a code block, it is resolved using the nearest enclosing
scope.  The set of all such scopes visible to a code block is called the block’s
environment.
在一个代码块内使用名字时,它会使用最接近的封闭(enclosing)作用域进行解析。对于代码块,可见作用域集合叫做块的 环境 ( environment )。
If a name is bound in a block, it is a local variable of that block, unless
declared as
nonlocal
.  If a name is bound at the module level, it is
a global variable.  (The variables of the module code block are local and
global.)  If a variable is used in a code block but not defined there, it is a
free variable.
如果某个名字绑定在代码块内,并且不是用
nonlocal
声明的,就称为它是这个块内的局部变量。如果名字绑定在模块级别上,它就是全局变量(模块代码块的变量是局部的,也是全局的)。如果某名字在代码块中有所使用,但并不在该块中定义,就称它为 自由变量 ( free variable ) 。
When a name is not found at all, a
NameError
exception is raised.  If the
name refers to a local variable that has not been bound, a
UnboundLocalError
exception is raised.  
UnboundLocalError
is a
subclass of
NameError
.
如果没有找到名字所需的绑定,就抛出异常
NameError
。如果名字引用的局部变量是没有绑定的,就抛出异常
UnboundLocalError

UnboundLocalError

NameError
的一个子类。
The following constructs bind names: formal parameters to functions,
import
statements, class and function definitions (these bind the
class or function name in the defining block), and targets that are identifiers
if occurring in an assignment,
for
loop header, or after
as
in a
with
statement or :keyword.`except` clause.
The
import
statement
of the form from ... import * binds all names defined in the imported
module, except those beginning with an underscore.  This form may only be used
at the module level.
以下构造可以绑定名字: 函数的形式参数、
import
语句、类和函数定义 (在定义块中绑定类或函数名字)以及赋值语句的目标标识符、
for
循环头、
出现在
with
语句或者
except
子句之后的
as
语句、以 from ... import * 形式出现的
import
语句会绑定导入模块中的所有名字(以下划线开始的名字除外),这种形式仅用于模块级别上。
A target occurring in a
del
statement is also considered bound for
this purpose (though the actual semantics are to unbind the name).  It is
illegal to unbind a name that is referenced by an enclosing scope; the compiler
will report a
SyntaxError
.
del
语句的目标也是作为一个名字绑定出现的(虽然整条语句的功能是解除绑定)。试图解除在另外封闭作用域引用的名字的绑定是不合法的,编译器会抛出异常
SyntaxError

Each assignment or import statement occurs within a block defined by a class or
function definition or at the module level (the top-level code block).
所有的赋值语句、import语句都必须出现在类定义或者函数定义块,或者模块级别上(顶级代码块上)。
If a name binding operation occurs anywhere within a code block, all uses of the
name within the block are treated as references to the current block.  This can
lead to errors when a name is used within a block before it is bound.  This rule
is subtle.  Python lacks declarations and allows name binding operations to
occur anywhere within a code block.  The local variables of a code block can be
determined by scanning the entire text of the block for name binding operations.
如果一个代码块内任何地方出现了某名字绑定操作,那么在该代码块内这个名字的使用都会被认为是对当前块内的引用(即局部变量)。如果一个名字在绑定
它之前使用的话就会导致错误。这个规则有些微妙。Python缺少声明,并且允许名字绑定操作发生任何地方。以名字绑定为目的扫描整个代码块,就可以检测
出代码块中的局部变量。
If the
global
statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the top-level
namespace.  Names are resolved in the top-level namespace by searching the
global namespace, i.e. the namespace of the module containing the code block,
and the builtins namespace, the namespace of the module
builtins
.  The
global namespace is searched first.  If the name is not found there, the builtins
namespace is searched.  The global statement must precede all uses of the name.
如果代码块内出现了
global
语句,那么使用以这条语句指定的名字时,都会引用顶层名字空间中的绑定。在顶层名字空间解析的名字,首先会搜索全局名字空间(即包含代码块的模块的名字空间),如果没有找到,会再搜索内置名字空间(模块
builtins
的名字空间)。global语句必须在使用相应全局变量之前使用。
The built-in namespace associated with the execution of a code block is actually
found by looking up the name __builtins__ in its global namespace; this
should be a dictionary or a module (in the latter case the module’s dictionary
is used).  By default, when in the
__main__
module, __builtins__ is
the built-in module
builtins
; when in any other module,
__builtins__ is an alias for the dictionary of the
builtins
module
itself.  __builtins__ can be set to a user-created dictionary to create a
weak form of restricted execution.
代码块执行中的内置名字空间,实际上是通过查找名字 __builtins__ 做到的。这应该是一个字典,或者是一个模块(使用模块的字典)。默认情况下,在模块
__main__
里, __builtins__ 是内置模块
builtins
;在其他模块里, __builtins__ 是
builtins
模块字典的一个别名。 __builtins__ 也可以是一个用户创建的字典,以创建一种弱形式的受限执行环境。
Note
Users should not touch __builtins__; it is strictly an implementation
detail.  Users wanting to override values in the built-in namespace should
import
the
builtins
module and modify its
attributes appropriately.
用户不应该干涉 __builtins__ ,严格地讲,这属于实现的细节。希望覆盖内置名字空间的用户,应该使用导入
builtins
模块,适当修改它的属性。
The namespace for a module is automatically created the first time a module is
imported.  The main module for a script is always called
__main__
.
模块的名字空间是在第一次导入它时创建的。脚本的主模块通常都称为
__main__

The global statement has the same scope as a name binding operation in the same
block.  If the nearest enclosing scope for a free variable contains a global
statement, the free variable is treated as a global.
在同一个代码块里,global语句与名字绑定操作具有相同的作用域。如果某自由变量的最近封闭作用域包括一个global语句,那么这个自由变量就当作全局变量处理。
Note
这似乎不对,见以下代码:
# 先定义两个全局变量bb和cc
bb = 11
cc = 22
def a():
    cc = 66
    def b():
        global bb
        bb+=cc
        print(cc)
        print(b.__code__.co_freevars)
    b()
a() # 这会输出('cc',) 和 66;如果自由变量cc按全局变量处理,应该是22。
print(bb) # 这会输出 77
A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution.  The namespace of
the class definition becomes the attribute dictionary of the class.  Names
defined at the class scope are not visible in methods.
类语句是一条可以使用和定义名字的可执行语句。这些引用遵循名字解析的正常规则。类定义的名字空间会成为类的属性字典。类作用域内定义的名字在方法里是不可见的。
4.1.1. 与动态功能的交互(Interaction with dynamic features)

There are several cases where Python statements are illegal when used in
conjunction with nested scopes that contain free variables.
在几种情况下,在包括自由变量的嵌套作用域中使用某些Python语句是不合法的。
If a variable is referenced in an enclosing scope, it is illegal to delete the
name.  An error will be reported at compile time.
如果变量在封闭作用域内被引用了,删除它的名字就是非法的。这会导致编译时的一个错误。
If the wild card form of import — import * — is used in a function and
the function contains or is a nested block with free variables, the compiler
will raise a
SyntaxError
.
如果在函数里使用了 import * 式的 import 语句,并且函数包括或本身就是一个有自由变量的嵌套块,那么编译器会抛出异常
SyntaxError

The
eval()
and
exec()
functions do not have access to the full
environment for resolving names.  Names may be resolved in the local and global
namespaces of the caller.  Free variables are not resolved in the nearest
enclosing namespace, but in the global namespace.  
[1]
The
exec()
and
eval()
functions have optional arguments to override the global and local
namespace.  If only one namespace is specified, it is used for both.
函数
eval()

exec()
在解析名字时没有访问全部环境的能力。名字可以在调用者的局部和变局名字空间内解析。自由变量不会在最接近的封闭作用域内解析,而发生在全局作用域里。[1] 可以为函数
exec()

eval()
提供可选参数覆盖全局和局部名字空间。如果只提供了一个参数,这个参数就会用当作两种名字空间使用。
4.2. 异常(Exceptions)

Exceptions are a means of breaking out of the normal flow of control of a code
block in order to handle errors or other exceptional conditions.  An exception
is raised at the point where the error is detected; it may be handled by the
surrounding code block or by any code block that directly or indirectly invoked
the code block where the error occurred.
“异常”是一种打破代码块正常执行流的方法,用于处理错误和其他异常条件。异常会在检查到错误的点上抛出。它可以在就近的代码块内处理,也可能在调用(直接或者间接调用)错误发生块的代码块中处理。
The Python interpreter raises an exception when it detects a run-time error
(such as division by zero).  A Python program can also explicitly raise an
exception with the
raise
statement. Exception handlers are specified
with the
try
...
except
statement.  The
finally
clause of such a statement can be used to specify cleanup code which does not
handle the exception, but is executed whether an exception occurred or not in
the preceding code.
Python解释器会在发现运行时错误时(例如除零)抛出异常。Python程序也可以使用
raise
语句抛出异常。可以使用
try
...
except
指定异常处理者。这个语句的
finally
子句可以指定一段并不专门用于处理异常的代码,不过,这些代码无论异常出现与否都会得到执行。
Python uses the “termination” model of error handling: an exception handler can
find out what happened and continue execution at an outer level, but it cannot
repair the cause of the error and retry the failing operation (except by
re-entering the offending piece of code from the top).
Python采用了错误处理的“终结”模型:异常处理者能够找出发生了什么,并且在外层代码块里继续执行,但是它不能修复错误和重试失败的操作(除了重新进入“当事”代码)。
When an exception is not handled at all, the interpreter terminates execution of
the program, or returns to its interactive main loop.  In either case, it prints
a stack backtrace, except when the exception is
SystemExit
.
如果异常根本没有得到处理,解释器会结束程序的执行,或者返回到交互主循环中。无论是哪种情况,都会打印一个栈回溯信息,但发生
SystemExit
异常时除外。
Exceptions are identified by class instances.  The
except
clause is
selected depending on the class of the instance: it must reference the class of
the instance or a base class thereof.  The instance can be received by the
handler and can carry additional information about the exceptional condition.
异常是由一个类实例标识的。根据异常实例的类选择使用哪条
except
子句处理异常,这个子句必须引用这个实例的类或者父类。异常处理者可以接收这个实例,实例也能够携带异常条件的额外信息。
Note
Exception messages are not part of the Python API.  Their contents may change
from one version of Python to the next without warning and should not be
relied on by code which will run under multiple versions of the interpreter.
异常消息并不作为Python API的一部分。不同版本的Python可能没有任何警告的前提下修改其内容,因此要在多个版本的解释器上运行的代码不应该依赖于它。
See also the description of the
try
statement in section
The try statement
and
raise
statement in section
The raise statement
.
关于异常,也可以参考在
The try statement
一节关于:keyword:try 语句的介绍,以及
The raise statement
一节中
raise
语句的介绍。
Footnotes
[1]
This limitation occurs because the code that is executed by these operations
is not available at the time the module is compiled.
此限制源于这些操作所执行的代码在编译该模块还是无效的。
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/42957/showart_2106786.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP