The order of classes

Remco Gerlich scarblac at pino.selwerd.nl
Mon Mar 19 09:06:31 EST 2001


Daniel Klein <danielk at aracnet.com> wrote in comp.lang.python:
> Is it a requirement to place classes in a particular order if one class uses
> another in its __init__ method?

*In* its method, no. But below, you use it as a default argument for the
method, and those are evaluated when the 'def' is executed - and at that
moment, foo isn't defined yet, so you get an error.

> To illustrate this in its simplest form...
> 
> class bar:
>     def __init__(self, f = foo()):
>         pass
> 
> class foo:
>     def __init__(self):
>         pass
> 
> ...then at the interactive prompt...
> 
> >>> import foobar
> Traceback (innermost last):
>   File "<pyshell#0>", line 1, in ?
>     import foobar
>   File "C:\DanielK\python\foobar.py", line 1, in ?
>     class bar:
>   File "C:\DanielK\python\foobar.py", line 2, in bar
>     def __init__(self, x = foo()):
> NameError: There is no variable named 'foo'
> 
> ...however, it works if I reverse the order of the classes and put 'foo' before
> 'bar'.
> 
> I would like to keep my classes in a particular order but it does not appear
> that I can do this in all cases.

Don't use default arguments like this. You do realize, that even if you put
the definition of foo before bar, that every instance of bar will have 
*the same foo instance* as its default argument? The 'f = foo()' happens
only once, namely when the class is defined.

Try something like this:

class bar:
   def __init__(self, f = None):
      if f == None:
         f = foo()

class foo:
   pass
   

Now the 'f = foo()' happens when a bar instance is created, and at that
time, foo already exists.

-- 
Remco Gerlich



More information about the Python-list mailing list