52 lines
1.3 KiB
Python
52 lines
1.3 KiB
Python
class BoundedInt():
|
|||
|
|
def __init__(self, i, min, max):
|
||
|
|
"""
|
||
|
|
Create a bounded integer.
|
||
|
|
|
||
|
|
Args:
|
||
|
|
i (int): The initial value of the integer.
|
||
|
|
min (int): The minimum value of the integer.
|
||
|
|
max (int): The maximum value of the integer.
|
||
|
|
"""
|
||
|
|
self.i = i
|
||
|
|
if i < min or i > max:
|
||
|
|
raise ValueError(f"{i} is outside the range of [{min}, {max}].")
|
||
|
|
self.min = min
|
||
|
|
self.max = max
|
||
|
|
|
||
|
|
def __int__(self):
|
||
|
|
return self.i
|
||
|
|
|
||
|
|
def __index__(self):
|
||
|
|
return self.i
|
||
|
|
|
||
|
|
def __getattr__(self, name):
|
||
|
|
print(f"DEBUG: {type(name)=}, {name=}")
|
||
|
|
return lambda *args, **kwargs: None
|
||
|
|
|
||
|
|
def __add__(self, y):
|
||
|
|
if isinstance(y, BoundedInt):
|
||
|
|
i = y.i
|
||
|
|
else:
|
||
|
|
i = y
|
||
|
|
if self.i + i > self.max:
|
||
|
|
raise ValueError()
|
||
|
|
else:
|
||
|
|
return BoundedInt(self.i + i, self.min, self.max)
|
||
|
|
|
||
|
|
def __sub__(self, y):
|
||
|
|
if isinstance(y, BoundedInt):
|
||
|
|
i = y.i
|
||
|
|
else:
|
||
|
|
i = y
|
||
|
|
if self.i - i < self.min:
|
||
|
|
raise ValueError()
|
||
|
|
else:
|
||
|
|
return BoundedInt(self.i - i, self.min, self.max)
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
b1 = BoundedInt(1,0,2)
|
||
|
|
b2 = BoundedInt(1,0,2)
|
||
|
|
print(f"{b1.doo}")
|
||
|
|
b3 = b1+b2
|
||
|
|
|