博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
转-9.2. Python Scopes and Namespaces
阅读量:6684 次
发布时间:2019-06-25

本文共 6588 字,大约阅读时间需要 21 分钟。

  hot3.png

From:

Before introducing classes, I first have to tell you something about Python’s scope rules. Class definitions play some neat tricks(技巧) with namespaces, and you need to know how scopes and namespaces work to fully understand what’s going on. Incidentally(顺便说一句), knowledge about this subject is useful for any advanced Python programmer(高手).
Let’s begin with some definitions.
A namespace is a mapping from names to objects(命名空间是名称到对象的映射关系). Most namespaces are currently implemented as Python dictionaries(命名空间是用字典实现的), but that’s normally not noticeable in any way (except for performance), and it may change in the future. Examples of namespaces are: the set of built-in names (containing functions such as abs(), and built-in exception names); the global names in a module; and the local names in a function invocation. In a sense(就某种意义来说) the set of attributes of an object also form a namespace(对象的属性也构成命名空间). The important thing to know about namespaces is that there is absolutely no relation between names in different namespaces; for instance, two different modules may both define a function maximize without confusion — users of the modules must prefix it with the module name. (不同命名空间中的名称是没有关系的。)
By the way, I use the word attribute(属性) for any name following a dot — for example, in the expression z.real, real is an attribute of the object z. Strictly speaking, references to names in modules are attribute references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it. In this case there happens to be a straightforward mapping between the module’s attributes and the global names defined in the module: they share the same namespace!
Attributes may be read-only or writable. In the latter case, assignment to attributes is possible. Module attributes are writable(模块属性是可以修改的): you can write modname.the_answer = 42. Writable attributes may also be deleted with the del statement(可写属性也可以用del语句删除). For example, del modname.the_answer will remove the attribute the_answer from the object named by modname.
Namespaces are created at different moments and have different lifetimes(寿命). The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted(内置命名空间是在解释器启动的时候创建的,并且不能删除。内置模块叫__builtin__). The global namespace for a module is created when the module definition is read in(模块的全局命名空间是在模块定义被读入的时候创建的。模块名就是文件名,或__main__); normally, module namespaces also last until the interpreter quits. The statements executed by the top-level invocation of the interpreter, either read from a script file or interactively, are considered part of a module called __main__, so they have their own global namespace(模块__main__的命名空间是在解释器执行顶层调用的语句时创建的。). (The built-in names actually also live in a module; this is called __builtin__.)
The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that is not handled within the function. (Actually, forgetting would be a better way to describe what actually happens.) Of course, recursive invocations each have their own local namespace. (局部命名空间是在方法被调用时创建的,并且随方法调用完成而消失)
A scope is a textual region of a Python program where a namespace is directly accessible. “Directly accessible” here means that an unqualified reference to a name attempts to find the name in the namespace.
Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: (任何时候,至少有3个嵌套的命名空间可以直接访问)
•the innermost scope, which is searched first, contains the local names (结构命名空间)
•the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names (函数命名空间)
•the next-to-last scope contains the current module’s global names (模块-全局-命名空间)
•the outermost scope (searched last) is the namespace containing built-in names (内置命名空间)
If a name is declared global(除非声明为global变量,否则会创建同名的局部变量), then all references and assignments go directly to the middle scope containing the module’s global names. Otherwise, all variables found outside of the innermost scope are read-only (an attempt to write to such a variable will simply create a new local variable in the innermost scope, leaving the identically named outer variable unchanged).
Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module’s namespace. Class definitions place yet another namespace in the local scope. (类定义也是一种局部范围。)
It is important to realize that scopes are determined textually(文本的): the global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias the function is called. On the other hand, the actual search for names is done dynamically, at run time — however, the language definition is evolving towards static name resolution, at “compile” time, so don’t rely on dynamic name resolution! (In fact, local variables are already determined statically.)
A special quirk(怪癖) of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope(最内层的范围). Assignments do not copy data — they just bind names to objects(赋值只是绑定名称和对象关系). The same is true for deletions: the statement del x removes the binding(绑定) of x from the namespace referenced by the local scope. In fact, all operations that introduce new names use the local scope: in particular, import statements and function definitions bind the module or function name in the local scope. (The global statement can be used to indicate(指出) that particular variables live in the global scope.)

###########################test##################################

a = 1 #a - global
if 1: b = 2 #b - global

for c in range(5): #c - global

    d = 'd'  #d - global

def fun(f): #f - global

    b = 'b+'
    global e; e = 'e+' #declare global variable
    f = 'f+' #attempt to update the parameter
    print 'global:', a
    print 'global+if->local:', b
    print 'global+for:', c
    print 'global+for:', d
    print 'global+main:', e
    print 'parameter:', f

if __name__ == '__main__':

    e = 'e' # e - global
    f = 'f' # f - global
    fun(f)
    print '-' * 20
    print 'global:', a
    print 'global+if->local:', b
    print 'global+for:', c
    print 'global+for:', d
    print 'global+main:', e
    print 'parameter:', f
###########################test##################################

转载于:https://my.oschina.net/kuafu/blog/42686

你可能感兴趣的文章
一起入门Citrix_XenDesktop7系列 二-- 跟着图片通过XenDesktop7交付(发布)应用与共享桌面...
查看>>
SCTF-2014 writeup(部分)
查看>>
istio 监控,遥测 (理论)
查看>>
修改Windows Server 2008远程桌面连接端口
查看>>
Android获取指定目录下的文件代码
查看>>
新疆之春(二)魂牵梦绕赛里木湖
查看>>
Linux一键安装Aria2+Yaaw+FileManager实现BT磁力下载,并在线查看/观看
查看>>
安装wxPHP后,apache无法启动
查看>>
我的友情链接
查看>>
GitOSC和GitHub上传项目
查看>>
Linux学习记录-2015-08-20--常用命令1
查看>>
【动态规划】0-1背包问题原理和实现
查看>>
在Word 2007文档表格中设置行高度和列宽度
查看>>
android:layout_gravity和android:gravity
查看>>
关于MYSQL的一些命令
查看>>
SCCM 2016 为客户端分发管理组件Configuration Manager(一)
查看>>
交换机SPAN功能配置
查看>>
Restful学习随笔
查看>>
CurrentRowColor 选中行 颜色改变
查看>>
内容溢出显示省略号
查看>>