CodeBlanks Logo Icon CodeBlanks

Data descriptor

Learn data descriptors with both __get__ and __set__.

What is a data descriptor?

A data descriptor implements both __get__ and __set__ (and optionally __delete__). Because it controls write access it is the most powerful kind.

The __set__(self, obj, value) signature intercepts the write moment. Inside it you can validate, transform or reject the value. It overrides any same-named entry in the instance dict (obj.__dict__); so even when written at instance level the descriptor always kicks in. This makes data descriptors reliable validation tools.

Validation with __set__

Inside __set__(self, obj, value) you validate with an if. If invalid you raise ValueError; if valid you store self.value = value.

The key point: the value lives on the descriptor, not the instance. So self.value belongs to the descriptor object. Since the same descriptor object exists once at class level, all instances share one value. If you want per-instance values you must use obj.__dict__; but for simple validation storing on the descriptor is fine.

Practice Validated data descriptor

Write a NonNegative data descriptor. Store an initial value with __init__(self, value=0). __get__(self, obj, objtype=None) returns self.value. In __set__(self, obj, value) raise ValueError if the value is less than 0; otherwise set self.value = value. In a Score class define points = NonNegative(0). Create an instance, set points = 10 and print it.

Starter code

main.py
# Write the NonNegative descriptor
# use it in the Score class
# print the value

Sample solution

main.py
# Write the NonNegative descriptor
class NonNegative:
    def __init__(self, value=0):
        self.value = value
    def __get__(self, obj, objtype=None):
        return self.value
    def __set__(self, obj, value):
        if value < 0:
            raise ValueError("negatif")
        self.value = value

class Score:
    points = NonNegative(0)

s = Score()
s.points = 10
print(s.points)

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match data descriptor concepts

Term Meaning
__get__ Intercepts read
__set__ Intercepts write
__delete__ Intercepts delete
data descriptor Both get and set

2 Which methods does a data descriptor include?

  • Only __set__
  • Only __get__
  • __get__ and __set__ Correct answer
  • Only __delete__

Explanation: answer: __get__ and __set__. A data descriptor implements both.

3 Complete the __set__ signature

Question
def __set__(self, obj, ____):
    self.value = value
Answer
def __set__(self, obj, value):
    self.value = value

Explanation: The value parameter carries the new value to assign.

All lessons in Expert