Properties with @property
Sometimes you want an attribute that's calculated, not stored. The @property decorator lets you define a method that's accessed like an attribute.
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
return 3.14159 * self.radius ** 2
Access it without parentheses:
c = Circle(5)
print(c.area) # 78.5... (no parentheses!)
The area is calculated each time you access it, always reflecting the current radius. It looks like an attribute but runs code behind the scenes.
Properties are Python's way of adding getters and setters without ugly syntax.
I cover properties in my Python OOP course.