The property decorator lets you use methods like attributes. It helps keep your code clean and easy to use.
Property decorator usage in Python
class ClassName: @property def attribute(self): # code to get the value pass @attribute.setter def attribute(self, value): # code to set the value pass @attribute.deleter def attribute(self): # code to delete the value pass
The @property decorator makes a method act like a read-only attribute.
Use @attribute.setter to allow changing the attribute value.
name. You can get the name but not change it directly.class Person: def __init__(self, name): self._name = name @property def name(self): return self._name
class Person: def __init__(self, age): self._age = age @property def age(self): return self._age @age.setter def age(self, value): if value < 0: raise ValueError("Age cannot be negative") self._age = value
This program creates a rectangle with width and height. It uses properties to get and set width and height safely. The area is a read-only property calculated from width and height.
class Rectangle: def __init__(self, width, height): self._width = width self._height = height @property def area(self): return self._width * self._height @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError("Width must be positive") self._width = value @property def height(self): return self._height @height.setter def height(self, value): if value <= 0: raise ValueError("Height must be positive") self._height = value rect = Rectangle(4, 5) print(f"Area: {rect.area}") rect.width = 10 print(f"New area: {rect.area}")
Properties let you change how attributes work without changing how you use them.
Use a leading underscore (like _width) to mark internal variables that should not be accessed directly.
Trying to set a read-only property without a setter will cause an error.
The @property decorator makes methods behave like attributes.
You can add setters and deleters to control how attributes are changed or removed.
Properties help keep your class interface simple and safe.