Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><code>get_zeus_name_1()</code> is trying to access the global variable <code>zeus</code>, which has not yet been initialised at the moment when <code>get_zeus_name_1()</code> is called.</p> <p><code>get_zeus_name_2()</code> takes an argument (<code>scope</code>) and accesses that, which works. It doesn't try to access the global variable <code>zeus</code>.</p> <p>Same story with <code>get_name_1()</code> and <code>get_name_2()</code>.</p> <p>I think the key point is to understand how python executes this line:</p> <pre><code>zeus=Zeus() </code></pre> <p>This line says to python: execute the method <code>Zeus()</code> (which is another name for the <code>__init__(self)</code> method in the <code>Zeus</code> class), and then assign the object returned by that method to the global variable <code>zeus</code>.</p> <p>Python first executes the method <code>Zeus()</code> and then, <em>after</em> the init method has finished executing and returned an object-instance of the Zeus class, python assigns that object to the global variable zeus. So the global variable zeus has not been defined until after the init method finishes, so get_name_1() and get_zeus_name_1() cannot access it.</p> <p>get_name_2() and get_zeus_name_2() access the same object-instance of the Zeus class as get_name_1() and get_zeus_name_1() try to access, but they access it via a parameter that is passed to them, not via the global variable, so they don't run into the problem.</p> <p>Here is a simpler example that demonstrates exactly the same problem:</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __init__(self): ... self.name = 'foobar' ... print self.name ... print foo.name ... &gt;&gt;&gt; foo = Foo() foobar Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 5, in __init__ NameError: global name 'foo' is not defined &gt;&gt;&gt; </code></pre> <p>The <code>print self.name</code> line works just fine (equivalent to get_name_2() and get_zeus_name_2()), but the <code>print foo.name</code> line crashes (equivalent to get_name_2() and get_zeus_name_2()).</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