Python Practice › OOP Programs › Program 19
Property decorator
Write a Python class that uses @property for a validated attribute.
Output
150 Error: price cannot be negative
Approach
- A getter with
@propertyand a setter with@<name>.setter.
Solution
class Product: def __init__(self, price): self.price = price @property def price(self): return self._price @price.setter def price(self, value): if value < 0: raise ValueError("price cannot be negative") self._price = value p = Product(100)p.price = 150print(p.price)try: p.price = -1except ValueError as e: print("Error:", e)Output
150 Error: price cannot be negative
Line by line
Line 3
Even the constructor goes through the setter, so invalid prices are rejected everywhere.
Learn the concept
New to this topic? Read the lesson, then come back.