[Python Wpg] Descriptors

Stuart Williams stuartw at mts.net
Wed Oct 31 08:38:22 EDT 2007


Good resource.  I'm aware of property but haven't used it
consistently.  Here's a snippet of the old code I presented last week
and a new untested version which uses property instead of __getattr__.

# Old
class Event:
    def __str__(self):
        return '%2d  %6s  %s' % (self.EventClass, self.Duration, \
                                 (self.TextData[:30] if self.TextData else ''))

    def __getattr__(self, name):
        if name is not 'spname':
            raise AttributeError
        self.spname = e.TextData.split()[0]
        return self.spname


# New
class Event(object):
    def __str__(self):
        return '%2d  %6s  %s' % (self.EventClass, self.Duration, \
                                 (self.TextData[:30] if self.TextData else ''))

    def get_spname(self):
        if not hasattr(self, '__spname'):
            self.__spname = e.TextData.split()[0]
        return self.__spname

    def set_spname(self, value):
        # needed to make spname a data descriptor
        raise AttributeError

    spname = property(get_spname, set_spname, None, "Stored procedure name")

On 10/30/07, Sydney Weidman <syd at plug.ca> wrote:
> This page about descriptors and the descriptor protocol touches on some
> of what Stuart was talking about at the last meeting with respect to
> when __getattr__ method is invoked:
>
> http://users.rcn.com/python/download/Descriptor.htm
>
> I found the document interesting and helpful, as was Stuart's
> presentation.
>
> - Syd
>
>
> _______________________________________________
> Winnipeg mailing list
> Winnipeg at python.org
> http://mail.python.org/mailman/listinfo/winnipeg
>



More information about the Winnipeg mailing list