0 votes
in Python by
What are Python descriptors?

1 Answer

0 votes
by

Python descriptors allow a programmer to create managed attributes.

In other object-oriented languages, you will find getter and setter methods to manage attributes.

However, Python allows a programmer to manage the attributes simply with the attribute name, without losing their protection.

This is achieved by defining a descriptor class, that implements any of __get__, __set__, __delete__ methods.

Descriptors - Example

Example 1

class EmpNameDescriptor:

    def __get__(self, obj, owner):

        return self.__empname

    def __set__(self, obj, value):

        if not isinstance(value, str):

            raise TypeError("'empname' must be a string.")

        self.__empname = value

The descriptor, EmpNameDescriptor is defined to manage empname attribute.

It checks if the value of empname attribute is a string or not.

Related questions

0 votes
asked Oct 14, 2021 in Python by rajeshsharma
0 votes
asked Sep 24, 2021 in Python by Robin
...