implementing descriptors

Raymond Hettinger python at rcn.com
Sat Aug 15 09:10:36 CEST 2009


> Raymond,
>    This functionality is exactly what I was looking for. Thanks!  I'll
> be using this to solve my problem.
>
>    Now that I'm on the right track, I'm still a bit confused about how
> __get__ and __set__ are useful.  Admittedly, I don't need to
> understand them to solve this problem, but perhaps they may be useful
> in the future.  If I wanted to solve this problem using __get__ and
> __set__ could it be done?

The __get__ and __set__ methods are used to implement property()
itself.
So, if you didn't have property, you could roll your own version:

class MyProperty(object):

    def __init__(self, fget, fset):
        self.fget = fget
        self.fset = fset

    def __get__(self, obj, objtype=None):
        return self.fget(obj)

    def __set__(self, obj, value):
        self.fset(obj, value)


class foo(object):
    def __init__(self,a = None,b = None):
        self._start = a
        self._end = b
    def get_start(self):
        return self._start
    def set_start(self, value):
        if self._end is None or value < self._end:
            self._start = value
        else:
            self._end = value
    start = MyProperty(get_start, set_start)
    def get_end(self):
        return self._end
    def set_end(self, value):
        if self._start is None or value > self._start:
            self._end = value
        else:
            self._start = value
    end = MyProperty(get_end, set_end)


Raymond




More information about the Python-list mailing list