I need to create several objects that have (often circular) references to each other. In general, several objects might be involved, but here's one simple case where I need just a pair of cars that refer to each other:
class Car:
def __init__(self, position, speed):
self.position = position
self.speed = speed
def set_reference(self, other_car):
self.other_car = other_car
# ...
def main():
# ...
car1 = Car(pos1, spd1)
car2 = Car(pos2, spd2)
car1.set_reference(car2)
car2.set_reference(car1)
A car without a reference to the other car is not a valid object. So ideally, I'd like to perform set_reference
from inside the __init__
method; this would be both safer (no chance of using invalid objects) and cleaner (all initialization will be performed in __init__
as one might expect).
Is there any neat solution that achieves this goal? I don't mind creating a pair of cars at once, but each car is a standalone entity, and so it needs to be an instance in its own right.
I'm also aware that circular references are troublesome for GC; I'll deal with that.
Use case:
Each car serves as a backup for the other. Car instances are "smart", i.e., they can do a lot of work. It's annoying if the a car instance doesn't know its backup, since it prevents a car from completing actions without requiring a reference from outside every time.