Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>At first the function call <code>fun2</code> in the original code didn't work. It would throw the error message: <code>NameError: global name fun1' is not defined</code>. <strong>Is it because functions have to be declared before they are called?</strong></p> <p>No.It turns out that the exception was thrown because <code>fun1</code> is <em>outside</em> the scope of <code>fun2</code>. Understanding how namespaces work will illuminate the exception as well as answer the posted question.</p> <p>The namespace of any function is first its own function namespace and then the global namespace. It doesn't, by default, include the 'class' namespace. But, it does (and should) have access to the class namespace. To let a function know that a it is calling a function that lives in the same class, one must use the <code>self</code> keyword before the calling function. </p> <p>This, then, works:</p> <pre><code>class Example: def fun2(self): self.fun1() # Notice the `self` keyword tells the interprter that # we're looking for a function, `fun1`, that is relative to # the same object (once a variable is declared as an Example # object) where `fun2` lives. def fun1(self): print "fun1 has been called" # fun1 has been called </code></pre> <p>Now <code>fun1</code> is reference-able by <code>fun2</code>, because <code>fun2</code> will now look at the class namespace. I tested that this is true by running:</p> <pre><code>class Example: def fun2(self): fun1() def fun1(self): print "fun1 was called" def fun1(): print "fun1 outside the class was called" </code></pre> <p>Without the <code>self</code> keyword the output is:</p> <pre><code>fun1 outside the class was called </code></pre> <p>So, to answer the question here, when python interprets a script it pre-compiles all the relevant namespaces. Therefore all functions are aware of all other functions that are appropriately addressed, rendering the original declaration order irrelevant.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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