L4·OOP & Errors

🎛️Properties & Descriptors

Computed attributes and the descriptor protocol.

propertydescriptorgettersetter

§ 1@property

Turn a method into a read-only attribute. Add @x.setter for writes and @x.deleter for delete.

§ 2Descriptors

A class implementing __get__/__set__/__delete__ is a descriptor. property is built on this.

Example

1class Circle:
2 def __init__(self, r): self.r = r
3 @property
4 def area(self):
5 return 3.14159 * self.r ** 2
6
7c = Circle(5)
8print(c.area) # attribute access, but computed

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
Accessing c.area calls: