Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question