Properties

Getters, setters with @property

Interview Relevant: Encapsulation

Properties

Managed attributes with getters and setters.

Code Examples

Properties for controlled access.

python
1class Circle:
2    def __init__(self, radius):
3        self._radius = radius
4
5    @property
6    def radius(self):
7        """Getter for radius."""
8        return self._radius
9
10    @radius.setter
11    def radius(self, value):
12        """Setter with validation."""
13        if value < 0:
14            raise ValueError("Radius must be positive")
15        self._radius = value
16
17    @property
18    def area(self):
19        """Computed property (read-only)."""
20        return 3.14159 * self._radius ** 2
21
22c = Circle(5)
23print(c.radius)   # 5 (uses getter)
24c.radius = 10     # Uses setter
25print(c.area)     # Computed property
26# c.area = 100    # Error! No setter

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In