Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Python resolves your variables with -- generally -- three namespaces available. </p> <blockquote> <p>At any time during execution, there are at least three nested scopes whose namespaces are directly accessible: the innermost scope, which is searched first, contains the local names; the namespaces of any enclosing functions, which are searched starting with the nearest enclosing scope; the middle scope, searched next, contains the current module's global names; and the outermost scope (searched last) is the namespace containing built-in names.</p> </blockquote> <p>There are two functions: <code>globals</code> and <code>locals</code> which show you the contents two of these namespaces.</p> <p>Namespaces are created by packages, modules, classes, object construction and functions. There aren't any other flavors of namespaces. </p> <p>In this case, the call to a function named <code>x</code> has to be resolved in the local name space or the global namespace.</p> <p>Local in this case, is the body of the method function <code>Foo.spam</code>.</p> <p>Global is -- well -- global. </p> <p>The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global. That's it.</p> <p>There are no other scopes. The <code>for</code> statement (and other compound statements like <code>if</code> and <code>try</code>) don't create new nested scopes. Only definitions (packages, modules, functions, classes and object instances.)</p> <p>Inside a class definition, the names are part of the class namespace. <code>code2</code>, for instance, must be qualified by the class name. Generally <code>Foo.code2</code>. However, <code>self.code2</code> will also work because Python objects look at the containing class as a fall-back.</p> <p>An object (an instance of a class) has instance variables. These names are in the object's namespace. They must be qualified by the object. (<code>variable.instance</code>.) </p> <p>From within a class method, you have locals and globals. You say <code>self.variable</code> to pick the instance as the namespace. You'll note that <code>self</code> is an argument to every class member function, making it part of the local namespace.</p> <p>See <a href="http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html" rel="nofollow noreferrer">Python Scope Rules</a>, <a href="https://stackoverflow.com/questions/146359/python-scope">Python Scope</a>, <a href="http://showmedo.com/videos/video?name=2800020&amp;fromSeriesID=280" rel="nofollow noreferrer">Variable Scope</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload