Skip to main content

Object-Oriented Python

Properties and Descriptors

0:00
LearnStep 1/3

Managing Attributes Idiomatically

In Python, direct attribute access is the norm. When you need to add validation or logic to getting/setting a value, you shouldn't switch to Java-style get_x()/set_x() methods, which would break client code. Instead, use properties and descriptors.

The @property Decorator

Use @property to define getters, setters, and deleters for an attribute while keeping the syntax obj.attr.

python

The Descriptor Protocol

Descriptors are the mechanism behind properties, methods, and class methods. A descriptor is a class that implements __get__, __set__, or __delete__. They allow you to reuse logic (like type checking) across many attributes.

python