Using a data descriptor

A data descriptor is used to build property-like processing using external class definitions. The descriptor methods of __get__(), __set__(), and __delete__() correspond to the way @property can be used to build getter, setter, and deleter methods. The important distinction of the descriptor is a separate and reusable class definition, allowing reuse of property definitions.

We'll design an overly simplistic unit conversion schema using descriptors that can perform appropriate conversions in their __get__() and __set__() methods.

The following is a superclass of a descriptor of units that will do conversions to and from a standard unit:

class Conversion:    """Depends on a standard value."""    conversion: float    standard: ...

Get Mastering Object-Oriented Python - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.