setting property to type other than what is given

Lee Harr missive at frontiernet.net
Sat May 8 15:30:22 EDT 2004


I am just starting to use properties, and wonder what you
might think of this ...


class RNumber(object):
    def __init__(self, n, nmin, nmax):
        self.nmin = nmin
        self.nmax = nmax
        self.n = n

    def _get_n(self):
        return self._n

    def _set_n(self, n):
        if n == 'max':
            self._n = self.nmax
        elif n == 'min':
            self._n = self.nmin
        else:
            self._n = min(self.nmax, n)
            self._n = max(self.nmin, self._n)

    n = property(_get_n, _set_n)


>>> a = RNumber(5, 0, 10)
>>> a.n
5
>>> a.n = -3
>>> a.n
0
>>> a.n = 'max'
>>> a.n
10
>>> a.nmax = 50
>>> a.n = 'max'
>>> a.n
50




More information about the Python-list mailing list