Gabriel C.
Gabriel C.

Reputation: 53

Cyclical reference of classes in Python

I have a handful of classes, and each create a reference of the next one upon __init__ initialization. However, I can't assign them through variables because you can't assign the first one to the last one because it doesn't exist yet:

class5= Class5(class1)  # UnresolvedReference here
class4= Class4(class5)
class3= Class3(class4)
class2 = Class2(class3)
class1= Class1(class2)

# There's also this, but it's the same thing

wiring = Class1(Class2(Class3(Class4(Class5(???)))))

How can that last one reference the first one? The classes need to be interchangeable, and any help would be welcome!

Upvotes: 0

Views: 55

Answers (1)

Michael Bianconi
Michael Bianconi

Reputation: 5242

Essentially, you want to do this:

foo = Foo(car)
baz = Baz(foo)
car = Car(baz)

You can't do this. You could try to do a lazy construction though, by having the constructor call an initialize() method if the given param is non-None.

foo = Foo(None)
baz = Baz(foo)
car = Car(baz)
foo.initialize(car)

Upvotes: 1

Related Questions