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:
- __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.
- __set__(self, obj, value): It is used to set the values of attributes. It returns None.
- __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:
- Check if the attribute (obj.x) you're looking for is a descriptor in the class.
- Check to see if it's a data descriptor. If it's a data descriptor, use its __get__ method.
- If it's not a data descriptor, look it up in __dict__ and return the result if it's found.
- 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 Python, Short-Circuiting in Python, Lambda Function in Python, and File Handling in Python.
Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System 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 problems, interview 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!