Circular Class Logic

Paul McGuire ptmcg at
Thu Mar 15 13:48:24 CET 2007

On Mar 15, 7:01 am, half.ital... at wrote:
> > Remove the line above
> > and add this below:
> > def initFoo():
> >   import baz
> >   Foo.baz = baz.Baz()
> > initFoo()
> I got it to work, but I had to add a check to see if the class
> variable had been set..
> def initBaz():
>   import Baz
>   Foo.baz = Baz.Baz()
> class Foo:
>   baz = None
>   def __init__(self):
>     if Foo.baz == None:
>       Foo.baz = True
>       initBaz()
> 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?
> > Instead of initFoo, you could use a custom metaclass. Or a class decorator (if
> > and when they become available...)
> I haven't tried either of those yet.  The names scare me. :)  Sounds
> like this might be a good time to explore them.
> > The code above is an effective way of doing what you want. But I'd think about
> > the actual need of doing such things - are you sure it's a good design?
> 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!
> ~Sean

Just initialize Folder at module level - see below.
-- Paul

class Folder(object):
    def __init__(self,path):
        self.path = path

    def __repr__(self):
        return self.__class__.__name__+"("+self.path+")"

class Disk(Folder):
    def __init__(self,driveLetter):

# hokey function to test if a drive letter points to a drive, I'm
# sure there's a better way
import os,string
def isDisk(d):
        os.stat(d + ":/")
        return True
        return False

# instead of calling some initFolder() method, just include this
# at module level in the module that declares both classes
Folder.allDisks = map(Disk,[d for d in string.uppercase if isDisk(d)])

# now can reference allDisks through Folder instances
f = Folder("C:/temp")
print f.allDisks

[Disk(C:/), Disk(D:/), Disk(E:/)]

More information about the Python-list mailing list