Or throw an exception
class Triangle: def __init__(self, a, b, c): sides = [a, b, c] sides.sort() if sides[0]+sides[1] < sides[2]: raise ValueError() self._a = a self._b = b self._c = c
or use assert (which raises the exception itself)
class Triangle: def __init__(self, a, b, c): sides = [a, b, c] sides.sort() assert sides[0]+sides[1] >= sides[2] self._a = a self._b = b self._c = c
Which one is more appropriate depends on whether invalid values should be selected as part of your API (first version) or only to search for programmer errors (second version, because statements will be skipped if you pass the -O "optimized" flag to the interpreter python).
source share