Examples of descriptors?

Aahz aahz at pythoncraft.com
Sat May 31 10:17:14 EDT 2003


In article <bba9u0$li0$1 at bob.news.rcn.net>,
Edward C. Jones <edcjones at erols.com> wrote:
>
>What, exactly, is a "descriptor"? The closest thing to a definition
>that I can find is: a class that defines __get__, __set__, and
>__delete__.  Where can I find some examples?

Simply put, a descriptor is an attribute of an object that is connected
to one or more functions.  For example:

    class C:
        def __init__(self):
            pass

__init__ is a get descriptor.  That's not a particularly useful addition
to the Python vocabulary unless you're working at the C API level,
though.  What brings descriptors to the fore is new-style classes and
properties:

    class C(object):
        def __init__(self):
            self._x = None
        def getx(self):
            return self._x
        def setx(self, value):
            self._x = value
        x = property(getx, setx)

x is now a property descriptor.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"In many ways, it's a dull language, borrowing solid old concepts from
many other languages & styles:  boring syntax, unsurprising semantics,
few automatic coercions, etc etc.  But that's one of the things I like
about it."  --Tim Peters on Python, 16 Sep 93




More information about the Python-list mailing list