Property decorator
Write a Python class that uses @property for a validated attribute.
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)150 Error: price cannot be negative
Line by line
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.