【发布时间】:2022-11-03 01:13:54
【问题描述】:
车库拥有汽车列表。
每辆车只能属于一个车库。
车库可以添加/移除汽车。
汽车可以移动车库。
车库需要跟踪他们拥有哪些汽车。
汽车需要存储它们所在的车库。
我有三个文件:
汽车.py
import garage
class Car:
def __init__(self, garage: garage.Garage):
self.garage = garage
self.garage.add_car(self)
def print_garage(self):
print(f"This car's garage is {self.garage}")
def move_garage(self, to_garage: garage.Garage):
self.garage.remove_car(self)
self.garage = to_garage
self.garage.add_car(self)
车库.py
import car
class Garage:
def __init__(self):
self.car_list = []
def add_car(self, car: car.Car):
self.car_list.append(car)
def remove_car(self, car: car.Car):
self.car_list.remove(car)
沙盒.py
from car import Car
from garage import Garage
new_garage = Garage()
new_garage2 = Garage()
new_car = Car(
garage=new_garage
)
new_car.move_garage(
to_garage=new_garage2
)
在当前状态下,我收到此错误
Exception has occurred: AttributeError
partially initialized module 'car' has no attribute 'Car' (most likely due to a circular import)
我尝试在两个类中使用各种“import car”、“from car import Car”、“from car import *”,并尝试在 sandbox.py 中以不同方式导入它们。
我尝试将所有内容都放在同一个文件中,但是由于 Car 和 Garage 相互依赖,所以这行不通。
我知道循环依赖通常是一件坏事,但我还没有设法找到可用于此类项目设计的替代方案。它似乎出现在我从事的许多项目中,所以我确定有些东西我没有看到!
【问题讨论】:
标签: python python-import