Getters and Setters

Controlled access to attributes

Interview Relevant: Encapsulation

Getters and Setters

Use @property for Pythonic getters/setters.

Code Examples

@property for managed attributes.

python
1class Circle:
2    def __init__(self, radius):
3        self._radius = radius
4
5    @property
6    def radius(self):
7        return self._radius
8
9    @radius.setter
10    def radius(self, value):
11        if value < 0:
12            raise ValueError("Must be positive")
13        self._radius = value
14
15c = Circle(5)
16print(c.radius)  # Getter
17c.radius = 10    # Setter

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In