Python Practice › OOP Programs › Program 19

Property decorator

EasyOOP Programs · 19 of 48

Write a Python class that uses @property for a validated attribute.

Advertisement
Output
150
Error: price cannot be negative

Approach

  1. A getter with @property and a setter with @<name>.setter.

Solution

Python
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.

More oop programs

← All 48 OOP Programs

Leave a Comment