implementing descriptors

dippim david.mcwright at usbfmi.com
Fri Aug 14 15:48:11 CEST 2009


On Aug 14, 2:34 am, Raymond Hettinger <pyt... at rcn.com> wrote:
> [David]
>
>
>
> > I am new to Python and I have a question about descriptors.  If I have
> > a class as written below, is there a way to use descriptors to be
> > certain that the datetime in start is always before the one in end?
>
> > class foo(object):
> >    def __init__(self,a = None,b = None)
> >       self.start = a
> >       self.end = b
>
> > from datetime import datetime
> > c = datetime(2009,8,13,6,15,0)
> > d = datetime(2009,8,14,12,0,0)
> > afoo = foo(c,d)
>
> > For instance, if the following code were run, I would like to instance
> > of foo to switch the start and end times.
>
> > afoo.start = datetime(2010,8,13,6,15,0)
>
> > I was thinking of using the __set__ descriptor to catch the assignment
> > and reverse the values if necessary, but I can't figure out how to
> > determine which values is being set.
>
> You're on the right track, but it is easier to use property() than to
> write your own custom descriptor with __get__ and __set__.
>
> 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 = property(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 = property(get_end, set_end)
>
> Raymond

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?

Thanks Again!



More information about the Python-list mailing list