Descriptor Examples

Let's figure out how descriptors can be used with the help of a few examples.

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:

Press + to interact
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 ...

Get hands-on with 1400+ tech skills courses.