Skip to content
Python

Property Decorator

Control attribute access with property.

By EZ4Code Team
propertyproperty

Code

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value < 0:
            raise ValueError("Radius cannot be negative")
        self._radius = value

    @property
    def area(self):
        import math
        return math.pi * self._radius ** 2

c = Circle(5)
print(c.area)
c.radius = 10

Explanation

property turns methods into attribute access, allowing validation on assignment.

More Python Snippets