📄 65.html
字号:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<META NAME="Robots" content="INDEX,NOFOLLOW">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<TITLE>Safari | Python Essential Reference, Second Edition -> Scoping Rules</TITLE>
<LINK REL="stylesheet" HREF="oreillyi/oreillyM.css">
</HEAD>
<BODY bgcolor="white" text="black" link="#990000" vlink="#990000" alink="#990000" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="100%" cellpadding=5 cellspacing=0 border=0 class="navtopbg"><tr><td><font size="1"><p class="navtitle"><a href="2.html" class="navtitle">Linux/Unix</a> > <a href="0735710910.html" class="navtitle">Python Essential Reference, Second Edition</a> > <a href="61.html" class="navtitle">6. Functions and Functional Programming</a> > <span class="nonavtitle">Scoping Rules</span></p></font></td><td align="right" valign="top" nowrap><font size="1"><a href="main.asp?list" class="safnavoff">See All Titles</a></font></td></tr></table>
<TABLE width=100% bgcolor=white border=0 cellspacing=0 cellpadding=5><TR><TD>
<TABLE border=0 width="100%" cellspacing=0 cellpadding=0><TR><td align=left width="15%" class="headingsubbarbg"><a href="64.html" title="Parameter Passing and Return Values"><font size="1">< BACK</font></a></td><td align=center width="70%" class="headingsubbarbg"><font size="1"><a href="popanote.asp?pubui=oreilly&bookname=0735710910&snode=65" target="_blank" title="Make a public or private annnotation">Make Note</a> | <a href="65.html" title="Use a Safari bookmark to remember this section">Bookmark</a></font></td><td align=right width="15%" class="headingsubbarbg"><a href="66.html" title="Recursion"><font size="1">CONTINUE ></font></a></td></TR></TABLE>
<a href="5%2F28%2F2002+8%3A58%3A54+PM.html" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><font color=white size=1>155117184014003188065099048180054212144238241179195140058238110137104016132046068203195106</font><a href="read8.asp?bookname=0735710910&snode=65&now=5%2F28%2F2002+8%3A58%3A54+PM" TABINDEX="-1"><img src=images/spacer.gif border=0 width=1 height=1></a><br>
<FONT>
<h3>Scoping Rules</h3>
<p>Each time a function executes, a new local namespace is created. This namespace contains the names of the function parameters, as well as the names of variables that are assigned inside the function body. When resolving names, the interpreter first searches the local namespace. (See the comments on the next page regarding nested scopes.) If no match exists, it searches the global namespace. The global namespace for a function is always the module in which the function was defined. If the interpreter finds no match in the global namespace, it makes a final check in the built-in namespace. If this fails, a <tT CLAss="monofont">NameError</tt> exception is raised.</P>
<P>One peculiarity of namespaces is the manipulation of global variables from within a function. For example, consider the following code:</P>
<Pre>
a = 42
def foo():
a = 13
foo()
print a </prE>
<P>When executed, the value <TT class="monofont">42</tt> prints, despite the appearance that we might be modifying the variable <tt class="monofont">a</tt> inside the function <tt clAss="monofont">foo</Tt>. When variables are assigned in a function, they抮e always bound to the function抯 local namespace; as a result, the variable <tt Class="monofont">a</Tt> in the function body refers to an entirely new object containing the value <tt CLASs="monofont">13</tt>. To alter this behavior, use the <tT CLAss="monofont">global</tt> statement. <TT CLass="monofont">global</tT> simply marks a list of names as belonging to the global namespace, and is necessary only when global variables will be modified. It can be placed anywhere in a function body and used repeatedly. For example:</P>
<PRe>
a = 42
def foo():
global a # 'a' is in global namespace
a = 13
foo()
print a </pre>
<p>All versions of Python allow nested function definitions. However, prior to Python 2.1, nested functions didn抰 provide nested scopes. As a result, a program using a nested function might not work as you expect. For example in Python 2.0, the following program is legal, but doesn抰 execute properly:</p>
<pre>
def bar():
x = 10
def spam(): # Nested function definition
print 'x is ', x # Looks for x in global scope of bar()
while x > 0:
spam() # Fails with a NameError on 'x'
x -= 1 </pre>
<p>In this case, when the nested function <tt class="monofont">spam()</Tt> executes, its global namespace is the same as the global namespace for <tT claSs="monofont">bar()</tt>, the module in which the function is defined. As a result, <tT claSS="monofont">spam()</TT> is unable to resolve any symbols in the namespace of <tt clASS="monofont">bar()</Tt> and fails with a <tt cLASS="monofont">NameError</tt>.</p>
<p>Starting with Python 2.1, support for nested scopes is provided (so the above example will work). With nested scopes, names are resolved by first checking the local scope and then all enclosing scopes. If no match is found, the global and built-in namespaces are checked as before. Note that in Python 2.1 nested scopes are an optional feature that must be enabled by including <TT CLass="monofont">from _ _future_ _ import nested_scopes</tt> in your program (see <a href="97.html">Chapter 10</a>, 揈xecution Environment
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -