Descriptor Guide

作者 :

Raymond Hettinger

联络 :

<python at rcn dot com>

Descriptors let objects customize attribute lookup, storage, and deletion.

This guide has four major sections:

  1. The “primer” gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you’re new to descriptors.

  2. The second section shows a complete, practical descriptor example. If you already know the basics, start there.

  3. The third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don’t need this level of detail.

  4. The last section has pure Python equivalents for built-in descriptors that are written in C. Read this if you’re curious about how functions turn into bound methods or about the implementation of common tools like classmethod() , staticmethod() , property() ,和 __slots__ .

Primer

In this primer, we start with the most basic possible example and then we’ll add new capabilities one by one.

简单范例:返回常量的描述符

The Ten class is a descriptor whose __get__() method always returns the constant 10 :

class Ten:
    def __get__(self, obj, objtype=None):
        return 10