【问题标题】:How do I structure this small project?我如何构建这个小项目?
【发布时间】: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


    【解决方案1】:

    您的类之间的所有关系都是架构问题。但在您的情况下,您可以查看前向引用。

    来自 pep 文档

    当类型提示包含尚未定义的名称时,该定义可以表示为字符串文字,以便稍后解析。

    那就是你应该将你的类路径作为文字字符串传递,例如:

    class Car:
        def __init__(self, garage: 'garage.Garage'): # or 'Garage' if its in same file.
            self.garage = garage
            self.garage.add_car(self)
        # other attrs and methods..
    

    【讨论】:

      猜你喜欢
      • 2011-01-28
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 2016-11-25
      • 2013-06-09
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      相关资源
      最近更新 更多