Search code examples
pythonpython-3.xclassoopinstance

Use or access class instances directly in another class in Python


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 

Solution

  • 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