[Tutor] Order of functions
Michael P. Reilly
arcege@speakeasy.net
Tue, 10 Jul 2001 10:06:26 -0400 (EDT)
Praveen Pathiyil wrote
> Is the order of functions important in python ?
> Suppose that i have a class X. If i have functions a, b,c and if =
> 'a' calls 'b', is it necessaruy to define 'b' before 'a' or before 'b' =
> is being called.
The only requirement is that the function (or class) needs to be defined
before it is called. So:
class Eggs:
f = Toast() # Toast is not defined yet but is trying to be called
def __init__(self):
pass
def Toast():
pass
would fail when defining the class since func1 is not defined before it
is called. But:
def Spam():
f = Ham() # does not get executed until Spam is called
def Ham():
pass
Spam() # Ham is now defined
Would have no problem since Spam would still be defined but the code is
not called.
There is a similar problem with modules:
----- mod1.py -----
import mod2 # import mod2 before funct1 has been defined
def funct1():
pass
-------------------
----- mod2.py -----
import mod1 # import mod1 and trying to call funct1, but it isn't defined
print dir(mod1) # won't show funct1
mod1.funct1()
-------------------
Here, the problem is that import happens before the function definition.
It is not a requirement to put functions into a proper order, but it
is a VERY good idea to. The order I would suggest is: more complicated
functions go last, functions and classes that use fewer other callables
earlier. There can always be fun exceptions tho. ;)
Hope I'm coherent enough today. :/
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |