in Python by
Q:
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.

Click here to read more about Python
Click here to read more about Insurance

Related questions

+1 vote
asked Feb 12 in Python by SakshiSharma
0 votes
asked Jan 1 in Python by SakshiSharma
0 votes
asked Aug 30, 2020 in Python by sharadyadav1986
0 votes
asked Aug 29, 2020 in Python by Robindeniel
0 votes
asked Jun 28, 2020 in Python by Robindeniel
...