py_stepik/mod_oop/2.3_12_bag_of_things.py

60 lines
1.4 KiB
Python
Raw Normal View History

2024-04-09 14:32:49 +00:00
# https://stepik.org/lesson/701985/step/12?unit=702086
from typing import List
class Thing:
def __init__(self, name: str, weight: int):
self.name, self.weight = name, weight
def __repr__(self):
return f"{self.__class__.__name__}({self.name!r}, {self.weight!r})"
class Bag:
def __init__(self, max_weight: int):
self.__things: List[Thing] = []
self.max_weight = max_weight
def __repr__(self):
return f"{self.__class__.__name__}({self.max_weight!r})"
@property
def weight(self) -> int:
return sum(t.weight for t in self.__things)
@property
def remaining_weight(self) -> int:
return self.max_weight - self.weight
@property
def things(self) -> List[Thing]:
return self.__things
def add_thing(self, thing: Thing):
if self.remaining_weight >= thing.weight:
self.__things.append(thing)
def remove_thing(self, indx: int):
del self.__things[indx]
def get_total_weight(self) -> int:
return self.weight
bag = Bag(1000)
bag.add_thing(Thing("Книга по Python", 100))
bag.add_thing(Thing("Котелок", 500))
bag.add_thing(Thing("Спички", 20))
bag.add_thing(Thing("Бумага", 100))
w = bag.get_total_weight()
for t in bag.things:
print(f"{t.name}: {t.weight}")
def tests():
...
tests()