Storing value with limits in object

David wizzardx at gmail.com
Sun Jun 22 06:14:55 EDT 2008


On Sun, Jun 22, 2008 at 11:44 AM, Josip <fake.mail at noone.be> 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?
>

Not with normal vars, because = is a rebinding operator in Python,
rather than assignment.

You can do (close to) the above with object properties.

David.



More information about the Python-list mailing list