Как правильно создать __init__ класса, в котором содержится объект другого класса?

Происходит инициализация двух объектов следующим способом.

dough_product = Product('Тесто', 200, 20)
dough_ingredient = Ingredient(dough_product, 100)

Как правильно создать __init__ для второго объекта?

class Product:
    def __init__(self, title, calorific, cost):
        self.title = title
        self.calorific = calorific
        self.cost = cost

class Ingredient(Product):

    def __init__(self, product(), weight):
        self.weight = weight

Ответы (1 шт):

Автор решения: gil9red

Используйте метод super().__init__() чтобы вызвать конструктор у предка

Для удобства добавил __str__, чтобы увидеть значения объектов

Пример:

class Product:
    def __init__(self, title, calorific, cost):
        self.title = title
        self.calorific = calorific
        self.cost = cost

    def __str__(self) -> str:
        return f"Product(title={self.title}, calorific={self.calorific}, cost={self.cost})"


class Ingredient(Product):
    def __init__(self, product: Product, weight):
        super().__init__(product.title, product.calorific, product.cost)

        self.weight = weight

    def __str__(self) -> str:
        return f"Ingredient(title={self.title}, calorific={self.calorific}, cost={self.cost}, weight={self.weight})"


dough_product = Product('Тесто', 200, 20)
print(dough_product)
# Product(title=Тесто, calorific=200, cost=20)

dough_ingredient = Ingredient(dough_product, 100)
print(dough_ingredient)
# Ingredient(title=Тесто, calorific=200, cost=20, weight=100)
→ Ссылка