Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Classes and Special Methods

Properties and descriptors

Concept guide to Python properties and descriptors: managed attributes, getters, setters, validation, __get__, __set__ and __set_name__ with examples.

A property makes a method look like a plain attribute. Callers write obj.area and obj.area = 5, while your class runs code in the background to compute, check or log the value. That lets you start with a simple public attribute and add validation later without changing any calling code.

Properties are built on a more general mechanism, the descriptor protocol. A descriptor is an object stored in a class attribute that defines __get__, and optionally __set__ and __delete__. When Python reads or writes that attribute on an instance, it calls those methods. Functions, classmethod, staticmethod, property and __slots__ members are all descriptors.

Properties

Python Getter, setter and computed property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A property without a setter is read-only. Names with a leading underscore (_width) conventionally hold the real stored value.

Writing a descriptor

Python A reusable validating descriptor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

One descriptor class now validates any number of attributes, which is the advantage over copying property code.

Key rules

  • Data vs. non-data descriptors. A descriptor with __set__ or __delete__ is a data descriptor and beats the instance __dict__. One with only __get__ (like a function) is overridden by an instance attribute of the same name.
  • __get__(self, obj, objtype) receives obj=None when accessed on the class; return self there so Product.price still works.
  • __set_name__ (Python 3.6+) is called once at class creation with the attribute name, so descriptors need not repeat it.
  • Property inside __init__. Assign through the public name (self.width = width) so validation runs.
  • Deleter: add @width.deleter to support del obj.width.
  • Computed properties recompute every access. For an expensive value computed once, use functools.cached_property.
  • Descriptors live on the class, not on instances; assigning one to self.x does nothing special.
  • Avoid infinite recursion: inside a getter or setter use the underscore name, never the property name itself.