Search code examples
pythonpython-3.xpython-descriptors

Python descriptors


From the descriptor docs:

A descriptor can be called directly by its method name. For example, d.__get__(obj).

What would be an example of this with the following class?

class Descriptor:
    def __init__(self, color="red"):
        self.color = color

For example, what is d and what is obj? How would "d.__get__(obj)" be called with the above class/instance?


Solution

  • Working Example

    To make your example a descriptor, it needs to have a __get__() method:

    class Descriptor:
        def __init__(self, color="red"):
            self.color = color
        def __get__(self, obj, objtype=None):
            return obj.size + ' ' + self.color
    

    Use that descriptor in another class:

    class A:
         pair = Descriptor('green')
         def __init__(self, size):
              self.size = size
    

    Invoke the descriptor like this:

    >>> a = A('big')
    >>> a.pair
    'big green'
    

    Hope this working example helps :-)

    Key points

    1) A class is a descriptor if defines any one of __get__(), __set__(), or __delete__().

    2) Put it to work by making an instance of the descriptor and storing it as a class variable in another class.

    3) Invoke the descriptor with normal attribute lookup using the dot operator.

    That's really all there is to it :-)