Reputation: 290
I want to create a number that you can set a maximum and/or minimum value to. So it'd work like this:
>>> n = myNum(5, minimum=0, maximum=10)
>>> n += 10
>>> print(n)
10
>>> n = myNum(-12, minimum=3)
>>> print(n)
3
The problem is that however I try to implement it seems to become very tedius and long despite the fact that it seems like such a simple concept. Is there an elegant way to do this without, say, overriding every single magic method having to do with numbers?
Upvotes: 1
Views: 109
Reputation: 12938
This might be overkill. You could try creating your own class and then overloading operators on your class. You can create the class mynum
:
class mynum:
def __init__ (self, val, minval, maxval):
self.val = val
self.minval = minval
self.maxval = maxval
and declare your numbers in your code as instances of mynum
:
n = mynum(5, 0, 10) # for instance
Then you can overload operators on your class, so that it behaves the way that you want it to. For adding, put this inside of your mynum
class definition:
def __add__(self, operand): # overload things like n + 10
self.val += operand
if self.val > self.maxval: # replace checks with max(min(...)...) if you like
self.val = self.maxval
elif self.val < self.minval:
self.val = self.minval
return self.val
This post has some good info on a starting point for this. The down side is that this method would require that you overload every operator that could possibly give you an invalid value for your mynum
instance.
Upvotes: 0
Reputation: 4685
You should rather do something like that
n = min(max(5,10),0)
and
n = min(-12,3)
From your comment, you can make a convenient function :
def between_min_max(value, min_val, max_val):
return min(max(value, max_val), min_val)
and use it later in your code :
min_val = 0
max_val = 10
n = between_min_max(5,min_val,max_val)
# and you can reuse min_val, max_val later
Upvotes: 1