Skip to content

Instantly share code, notes, and snippets.

@dp-quant
Last active March 24, 2023 13:58
oop
class Building:
# do not use magic words
PLACE_OUT_OF_STOCK = 'Out of Stock'
PLACE_REMOTE_WAREHOUSE = 'Remove Warehouse'
# it's just an optimization
__slots__ = ['_material', '_color', '_number', '_store_place', '_original_place']
# lets make everything private
def __init__(self, material: str, color: str, store_place: str, number: int=0):
self._material = material or 'Undefined'
self._color = color or "Underfined"
self._store_place = self._original_place = store_place or "Undefined"
self._number = number
# Here is contaversial idea: quantity/number of the material should change object ste immidiatly
self.detect_place_to_store_materials()
def __str__(self):
return f"{self._store_place}:\n material: {self._material}\n color: {self._color}\n" \
f" quantity: {self._number}"
# Adding validations.
@property
def number(self):
return self._number
# Here is contaversial idea: quantity/number of the material should change object ste immidiatly
# Contaversial: cause we are breaking some SOLID rules, but in that "synthetic" case it looks like ok
@number.setter
def number(self, number: int):
if not (isinstance(number, int) and number >= 0):
raise ValueError("Positive numbers only")
# yep, it's ok for logs in general
if number > 100:
print("Check warehouse capacity first")
self._number = number
self.detect_place_to_store_materials()
# lets rename it a bit.
def detect_place_to_store_materials(self):
if self.number <= 0:
self._store_place = Building.PLACE_OUT_OF_STOCK
elif self.number >= 100:
self._store_place = Building.PLACE_REMOTE_WAREHOUSE
else:
self._store_place = self._original_place
# Checking if everything works
building_east = Building("wood", "oak", "East Warehouse", 3)
print(building_east)
building_west = Building("plastic", "green", "West Warehouse", 200)
building_west.number += 100
building_west.number -= 250
# I prefer not allow to change some attributes directly. Yes, we can add setters for all attributes, but... dont makes sense, just use python "private" fields notation
# new_b._place = new_b.choose_place()
print(building_west)
south_building = Building("steel", "grey", "South Beach Area", 120)
print(south_building)
south_building.detect_place_to_store_materials()
print(south_building)
undef_building = south_building = Building(None, None, None, 0)
print(south_building)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment