Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a descriptor
3.
Descriptor Protocol
4.
Access rules of the descriptor
5.
Frequently Asked Questions
5.1.
What are descriptors in python?
5.2.
What is descriptor protocol?
5.3.
What is the use of descriptors?
5.4.
What are the many kinds of descriptors?
5.5.
In Python, what is a __dict__?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Descriptors In Python

Introduction

You may have heard of the term "descriptor" in Python development. Most developers are unaware of its principle because we rarely utilize it directly. However, when you gain proficiency with Python and desire to advance, it is advised that you learn the theory of descriptors, which will also help you better comprehend Python's design ideas.

Also See, Intersection in Python, Swapcase in Python

What is a descriptor

In Python 2.2, a new concept called descriptor was added. Descriptors are most commonly used to implement the object system's fundamental functionalities, such as bound and unbound methods, class methods, and static method characteristics.

It is possible to add a class attribute to a class in Python, and this attribute is called a descriptor.

For example:

class student:
  name = 'John'
print(f'Name: {student.name}')
You can also try this code with Online Python Compiler
Run Code

 

We create a student class and assign the property's name and age to it. In addition to directly declaring class attributes, classes can also be used to define class attributes.

class student_info:
  def __get__(self, name, obj):
    self.name = 'John'
    return (self.name)

class student:
  name = student_info()
print(f'Name: {student.name}')
You can also try this code with Online Python Compiler
Run Code

 

The name is a class in the above code, not a specific value. ‘__get__’ function defined in ‘student_info’ class returns a specific value. Thus, using descriptors, you may simply change the way a class attribute is declared.

Also see, Fibonacci Series in Python and Convert String to List Python.

Check out Escape Sequence in Python

Descriptor Protocol

A class attribute would want to be handled by a class. This class's inner method cannot be defined arbitrarily; it must adhere to the "descriptor protocol."

When attributes are referenced in the model, the Python descriptors interface is used to trigger events. Python will translate attribute access operations specifically, and the descriptor protocol will specify the technique. We could use the descriptor protocol offered by Python to create functions that are equivalent to private attributes in Python.

There are several methods in the descriptor protocol:

  1. __get__(self, obj, type=None): It's used to get at attributes. It returns the attribute's value. If the attribute is invalid, it will throw a ValueError exception. It will throw an AttributeError if the attribute does not exist.
  2. __set__(self, obj, value): It is used to set the values of attributes. It returns None.
  3. __delete__(self, obj): It is used to delete the attributes and returns None.

Recommended Topic, Python for Data Science

 

Example

class Age:
    def __init__(self, age=16):
        self.age = age

    def __set__(self, obj, age):
        if not 10 <= age <= 20:
            raise ValueError('Valid age must be in [10, 20]')
        self.age = age


    def __get__(self, obj, type=None):
        return self.age

class Student:
    age = Age()

    def __init__(self, name, age):
        self.name = name
        self.age = age
        print(f'Student Name: {self.name}, Age:{self.age}')

S1 = Student("Alice", 13)
S2 = Student("Bob", 23)
You can also try this code with Online Python Compiler
Run Code

 

Output

Student Name: Alice, Age:13
Traceback (most recent call last):
  File "c:\Jaglike\Python\practice.py", line 23, in <module>
    S2 = Student("Bob", 23)
  File "c:\Jaglike\Python\practice.py", line 19, in __init__
    self.age = age
  File "c:\Jaglike\Python\practice.py", line 7, in __set__
    raise ValueError('Valid age must be in [10, 20]')
ValueError: Valid age must be in [10, 20]

You can compile it with online python compiler.

Also read,  Python filename extensions

Access rules of the descriptor

Python searches for attributes in a specific sequence, when we access them.

The entry point for all attribute searches is __getattribute__, and the internal implementation of attribute searches is as follows:

  1. Check if the attribute (obj.x) you're looking for is a descriptor in the class.
  2. Check to see if it's a data descriptor. If it's a data descriptor, use its __get__ method.
  3. If it's not a data descriptor, look it up in __dict__ and return the result if it's found.
  4. Re-evaluate the type of descriptor if it isn't found in __dict__.

 

Must Read Python List Operations

Frequently Asked Questions

What are descriptors in python?

In Python 2.2, a new concept called descriptor was added. Descriptors are most commonly used to implement the object system's fundamental functionalities, such as bound and unbound methods, class methods, and static method characteristics.

What is descriptor protocol?

When attributes are referenced in the model, the Python descriptors interface is used to trigger events. Python will translate attribute access operations specifically, and the descriptor protocol will specify the technique. 

What is the use of descriptors?

Descriptors are most commonly used to implement the object system's fundamental functionalities, such as bound and unbound methods, and static methods. It is possible to add a class attribute to a class in Python, and this attribute is a descriptor.

What are the many kinds of descriptors?

Data descriptors and non-data descriptors are the two sorts of descriptors.

In Python, what is a __dict__?

In Python, every object has an attribute called __dict__, which is a dictionary object that contains all of the object's attributes. To generate a dictionary, attributes are mapped to their values.

Conclusion

In this article, we studied in detail attribute descriptors in python. We also saw an example of how to use descriptors. We hope that this blog has helped you enhance your knowledge of the descriptors.

After reading about the descriptors in python, are you not feeling excited to read/explore more articles on the topic of Python? Don't worry; Coding Ninjas has you covered. To learn, see Exception & Errors in PythonShort-Circuiting in PythonLambda Function in Python, and File Handling in Python.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass