I
I
Igor Nikolaev2020-07-14 18:05:43
Python
Igor Nikolaev, 2020-07-14 18:05:43

How to properly unpack objects in a constructor?

Playing with toy code and suddenly realized my incompetence.
The code:

from random import randrange
from accessify import private


class Product:   # продукт, название, цена
    def __init__(self, name: str, price: float):
        self.name = name
        self.price = price

class FarmerCar:   # машина с продуктами
    def __init__(self, name: str, *products: Product):
        self.__trunk = {}   # багажник машины в виде словаря
        self.name = name
        self.__product_list = [*products]  # список продуктов
        self.load_products()   # загружаем продукты в багажник

    @property
    def trunk(self):   # багажник
        return self.__trunk

    @private
    def load_products(self):
        for prod in self.__product_list:
            if self.__trunk.get(prod.name):   
                number = self.__trunk[prod.name][1] + 1
                self.__trunk[prod.name] = [prod.price, number]
                print(prod.name)  #  метки
                print('+')
            else:
                self.__trunk[prod.name] = [prod.price, 1]
                print(prod.name)


class MiniMarket:  # продуктовый магазин
    def __init__(self, name: str, *cars: FarmerCar):   # передача в конструктор
        self.name = name
        self.__car_list = [*cars]   # список распакованных объектов
        print(len(self.__car_list))
        self.__storage = {}  # склад в виде словаря
        self.unpacking_database_to_market()   # выгрузка на склад склада по списку

    @property
    def storage(self):
        return self.__storage

    @private
    def unpacking_database_to_market(self):  # выгрузка машин на склад магазина
        for car in self.__car_list:
            for name, data in car.trunk.items():
                if self.__storage.get(name):
                    self.__storage[name][1] += car.trunk[name][1]
                else:
                    self.__storage[name] = data


a = Product('apple', 10)
b = Product('milk', 5)
c = Product('bread', 10)

dbb = FarmerCar('dsa', b, a)

market = MiniMarket('5', dbb, dbb, dbb, dbb, dbb, dbb, dbb, dbb, dbb, dbb, dbb)

print(dbb.trunk)

Output:
milk
apple
11
{'milk': [5, 1024], 'apple': [10, 1024]}

Accordingly, why does the property of FarmerCar objects change when the Minimarket object is initialized?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-07-14
@Kompl1990

In Python, objects are passed by reference, not by value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question