Descriptors in Python

Descriptors are Python objects that implement a method of the descriptor protocol, which gives you the ability to create objects that have special behaviour or  when they’re accessed as attributes of other objects. It increase an understanding of Python, and improve coding skills.

Descriptor is an object attribute with “binding behaviour ”. It establishes a connection between the attributes of classes. A descriptor is a mechanism behind properties, methods, static methods, class methods and super().

In descriptors we used three different methods that are __getters__()__setters__(), and __delete__(). If any of those methods are defined for an object, it can be termed as a descriptor. We use this methods like getters and setters to adjust the values on attributes without any special processing. It’s just a basic storage system.

Descriptor protocol :

Descriptors are a new way to implement classes in Python, and it does not need to inherit anything from a particular object. To implement descriptors easily in python we have to use at least one of the methods that are defined above.

Python descriptor protocol is simply a way to specify what happens when an attribute is referenced on a model. It allows a programmer to easily and efficiently manage attribute access.

There are three protocol in python descriptor for setters, getters and delete method. They are:

  • gfg.__get__(self, obj, type=None) : This type of attribute is called when we want to get the information (value = obj.attr), and whatever it returns is what will be given to the code that requested the attribute’s value.
  • gfg.__set__(self, obj, value) : It is called to set the values of an attribute (obj.attr ='value'), and it will not return anything to us.
  • gfg.__delete__(self, obj) : It is called when the attribute is deleted from an object (del obj.attr).

Example:

class MyDescriptor(object):

    def __init__(self, name =''):
        self.name = name
  
    def __get__(self, obj, objtype):
        return "{}for{}".format(self.name, self.name)

    def __set__(self, obj, name):
        if isinstance(name, str):
            self.name = name
        else:
            raise TypeError("Name should be a string")
          
class func(object):
    name = MyDescriptor()
    
a = func()
a.name = "abc"
print(a.name)

Output: abcforabc

Tags