Search code examples
pythonclass

Creating an instance of a class, before class is defined?


Here's an example of my problem :

class bar() :
    spam = foo()
    def test(self) :
        print self.spam.eggs
        pass

class foo() :
    eggs = 50

The issue (I assume) is that I'm trying to create an instance of a class before the class is defined. The obvious solution is to re-order my classes, but I like to keep my classes in alphabetical order (maybe a silly practice). Is there any way to define all my classes simultaneously? Do I just have to bite the bullet and reorder my class definitions?


Solution

  • Alphabetical order is a silly idea indeed;-). Nevertheless, various possibilities include:

    class aardvark(object):
        eggs = 50
    
    class bar(object):
        spam = aardvark()
        def test(self) :
            print self.spam.eggs
    
    foo = aardvark
    

    and

    class bar(object):
        spam = None  # optional!-)
        def test(self) :
            print self.spam.eggs
    
    class foo(object):
        eggs = 50
    
    bar.spam = foo()
    

    Note that much more crucial aspects than "alphabetical order" include making all classes "new style" (I've done it in both examples above) and removing totally redundant code like those pass statements (I've done that, too;-).