在 Python 中的另一个 class 中直接使用或访问 class 个实例

Use or access class instances directly in another class in Python

我正在尝试弄清楚如何访问 Python 中另一个 class 中的 class 实例。 在下面的示例中,我创建了两个 classes,housepaint,并且我想使用 house class 中的维度作为变量paint class:

class house:
  def __init__(self, length, width)
     self.length = length
     self.width = width

class paint:
  def __init__(self, color_paint, price):
    self.color_paint = color_paint
    self.price = price * (length * width) # <-- length and width from class house 

您可以将 House class 的实例传递给 Paint class 的初始化程序:

class House:
    def __init__(self, length, width):
        self.length = length
        self.width = width


class Paint:
    def __init__(self, color_paint, price, house):
        self.house = house
        self.color_paint = color_paint
        self.price = price * (self.house.length * self.house.width)

house_obj = House(4, 5)
paint_obj = Paint('blue', 1000, house_obj)

print(paint_obj.price)

输出:

20000   # which is 4 * 5 * 1000