Search⌘ K
AI Features

Descriptor Examples

Learn how to implement Python descriptors through clear examples. Understand their role in managing attribute access and validation, and see how descriptors work behind the scenes in Python classes. This lesson helps you apply descriptors effectively in your code.

At this point, we may be confused about how we would even use a descriptor. We always find it helpful when we are learning a new concept if we have a few examples that demonstrate how it works. So in this lesson, we will look at some examples so we will know how to use descriptors in our own code!

Simple example of data descriptor

Let’s start by writing a really simple data descriptor and then use it in a class. This example is based on Python’s documentation:

Python 3.5
class MyDescriptor():
"""
A simple demo descriptor
"""
def __init__(self, initial_value=None, name='my_var'):
self.var_name = name
self.value = initial_value
def __get__(self, obj, objtype):
print('Getting', self.var_name)
return self.value
def __set__(self, obj, value):
msg = 'Setting {name} to {value}'
print(msg.format(name=self.var_name, value=value))
self.value = value
class MyClass():
desc = MyDescriptor(initial_value='Mike', name='desc')
normal = 10
if __name__ == '__main__':
c = MyClass()
print(c.desc)
print(c.normal)
c.desc = 100
print(c.desc)

Here we create a class and define three magic methods:

  • __init__: our constructor which takes a value and the name of our variable (lines 5-7)
  • __get__: prints out the current variable name and returns the value (lines 9-11)
  • __set__: prints out the name of our variable and the value we just assigned and sets the value itself (lines 13-16)

Then we create a class that creates an instance of ...