Descriptors

Advanced attribute access control

Interview Relevant: Advanced Python

Descriptors

Objects that define attribute access.

Code Examples

Descriptors for validation.

python
1class Validator:
2    def __set_name__(self, owner, name):
3        self.name = name
4
5    def __get__(self, obj, objtype=None):
6        return obj.__dict__.get(self.name)
7
8    def __set__(self, obj, value):
9        if value < 0:
10            raise ValueError(f"{self.name} must be >= 0")
11        obj.__dict__[self.name] = value
12
13class Person:
14    age = Validator()
15
16    def __init__(self, age):
17        self.age = age

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In