Storing value with limits in object

Larry Bates larry.bates at websafe.com`
Sun Jun 22 09:53:29 EDT 2008


Josip wrote:
> I'm trying to limit a value stored by object (either int or float):
> 
> class Limited(object):
>     def __init__(self, value, min, max):
>         self.min, self.max = min, max
>         self.n = value
>     def set_n(self,value):
>         if value < self.min: # boundary check
>             self.n = self.min
>         if value > self.max:
>             self.n = self.max
>         else:
>             self.n = value
>     n = property(lambda self : self._value, set_n)
> 
> This works, except I would like the class to behave like built-in types, so
> I can use it like this:
> 
> a = Limited(7, 0, 10)
> b = math.sin(a)
> 
> So that object itself returns it's value (which is stored in a.n). Is this
> possible?
> 
> 
> 
Why not make it a function?

function assignLimited(value, vmin, vmax):
     value = max(vmin, value)
     value = min(vmax, value)
     return value


a = assignLimited(7, 0, 10)


Seems like it solves your problem relatively cleanly.
Note: I also removed min/max variables because they would mask the built-in 
min/max functions.

-Larry



More information about the Python-list mailing list