DEV Community

FaithInErrorsZORO
FaithInErrorsZORO

Posted on

Python classes ? being pythonic

class MassLessThanZeroException(Exception):
pass

class UnitNotDefinedException(Exception):
pass

class Mass:
_conversion = {
'mg': 0.000001,
'g': 0.001,
'kg': 1,
'lb': 0.453592,
'oz': 0.02835,
'stone': 6.35029
}

def __init__(self, value, unit='kg'):
    if not isinstance(value, (int, float)) or isinstance(value, bool):
        raise ValueError("Value must be a number")
    if value < 0:
        raise MassLessThanZeroException("Value cannot be negative")
    if unit not in self._conversion:
        raise UnitNotDefinedException("Unit cannot be used")

    self.value = value
    self.unit = unit

def convert_to_kg(self):
    return self.value * Mass._conversion[self.unit]

def __str__(self):
    return f"{self.convert_to_kg():.2f} kg"

def __repr__(self):
    return f"Mass({self.value:.2f}, '{self.unit}')"

def __add__(self, other):
    if isinstance(other, (int, float)):
        total = self.convert_to_kg() + other
    else:
        total = self.convert_to_kg() + other.convert_to_kg()
    return Mass(total / Mass._conversion[self.unit], self.unit)

def __iadd__(self, other):
    return self + other

def __radd__(self, other):
    return self + other

def __sub__(self, other):
    if isinstance(other, (int, float)):
        total = self.convert_to_kg() - other
    else:
        total = self.convert_to_kg() - other.convert_to_kg()
    return Mass(max(0, total) / Mass._conversion[self.unit], self.unit)

def __isub__(self, other):
    return self - other

def __rsub__(self, other):
    if isinstance(other, (int, float)):
        total = other - self.convert_to_kg()
    else:
        total = other.convert_to_kg() - self.convert_to_kg()
    return Mass(max(0, total) / Mass._conversion[self.unit], self.unit)

def __lt__(self, other):
    return self.convert_to_kg() < other.convert_to_kg()

def __gt__(self, other):
    return self.convert_to_kg() > other.convert_to_kg()

def __eq__(self, other):
    return abs(self.convert_to_kg() - other.convert_to_kg()) < 0.01
Enter fullscreen mode Exit fullscreen mode

Top comments (0)