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
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
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)receivesobj=Nonewhen accessed on the class; returnselfthere soProduct.pricestill 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.deleterto supportdel 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.xdoes nothing special. - Avoid infinite recursion: inside a getter or setter use the underscore name, never the property name itself.