Menu

Descriptors and Controlled Attributes in Python - MachineLearningMastery.com
🖼️

Descriptors and Controlled Attributes in Python - MachineLearningMastery.com

Reading 0:00
15s threshold

In this article, you will learn what Python descriptors are and how to use them to build three types of controlled attributes: validated, computed, and lazily loaded.

Topics we will cover include:

How to build a validated attribute descriptor that enforces type and range constraints on class attributes.

How to build a computed attribute descriptor that derives its value dynamically from another attribute.

How to build a lazily loaded attribute descriptor that defers expensive computations until the attribute is first accessed.

Introduction and Motivation

In Python, descriptors are a mechanism that governs what occurs when we access an object’s attribute, set it, or remove it. They are defined through a powerful protocol whereby a class implements special methods like __get__ , __set__ , and so on, to customize access to the attribute(s).

Meanwhile, controlled attributes are properties defined at the class level whose write, read, and delete logic is handled by the aforesaid descriptors.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.