1

I am trying to figure out how to access a class instance in another class in Python. In the example below I create two classes, house and paint, and I want to use the dimensions from the house class as a variable in the 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 
S.B
  • 13,077
  • 10
  • 22
  • 49
Matly
  • 13
  • 3
  • 1
    Which instance's attributes do you want to access? Just pass the instance as a parameter to your constructor(`__init__` method). – Axe319 Sep 15 '21 at 18:48

1 Answers1

1

You can pass an instance of House class to Paint class's initializer :

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)

output :

20000   # which is 4 * 5 * 1000
S.B
  • 13,077
  • 10
  • 22
  • 49