Circular Class Logic

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Mar 15 16:14:19 EDT 2007


En Thu, 15 Mar 2007 09:01:07 -0300, <half.italian at gmail.com> escribió:

> I got it to work, but I had to add a check to see if the class
> variable had been set..
>  class Foo:
>   baz = None
>   def __init__(self):
>     if Foo.baz == None:
>       Foo.baz = True
>       initBaz()

This is a different approach. You are using instance initialization  
(Foo.__init__) to finish class initialization. Foo.__init__ will be called  
each time you create a Foo instance; that's why you had to check if  
Foo.baz is None.
(BTW, Foo.baz=True is unneeded).
The only problem I can see is that the Foo class is not completely  
initialized until its first instance is created; this may not be a problem  
in your case.

> What exactly is being accomplished by having the init function outside
> of the class?  If there is no check, wouldn't it just execute every
> time an object is instantiated anyway?

What I intended was different:

==========
C:\TEMP>type foo.py
class Foo:
         baz = None

         def __init__(self):
                 pass

def initFoo():
         import baz
         Foo.baz = baz.Baz()
initFoo()

C:\TEMP>type bar.py
import foo

class Bar(foo.Foo):
         pass

C:\TEMP>type baz.py
import bar

class Baz(bar.Bar):
         pass

C:\TEMP>type test.py
import foo,bar,baz

print foo.Foo.baz
f = foo.Foo()
print f.baz
b = bar.Bar()
print b.baz
print baz.Baz.baz

C:\TEMP>python test.py
<baz.Baz instance at 0x00AD7B20>
<baz.Baz instance at 0x00AD7B20>
<baz.Baz instance at 0x00AD7B20>
<baz.Baz instance at 0x00AD7B20>
==========

initFoo is only executed when Foo is imported the first time. Note that  
you can't do that if

> I thought it was a good design, but now I'm not so sure.  I'm
> untrained, so often I dont know the right way to do things.  As I
> build this into the libraries, I'll keep an eye on how the code is
> developing and go from there.    Thanks for the help!

Usually Python code is quite concise and straightforward; when I find  
myself writing things too convoluted, I know it's time to  
refactor/redesign. (Anyway some things remain not as simple as I'd like  
:( )
Perhaps you later find the need for a different/better way.

--
Gabriel Genellina




More information about the Python-list mailing list