Code Explanation:
1. Defining the Descriptor Class
class Field:
A class named Field is defined.
This class is a descriptor because it implements the __get__ method.
2. Implementing the __get__ Method
def __get__(self, obj, owner):
return "system"
__get__ is automatically called when the attribute is accessed.
Parameters:
obj → the instance accessing the attribute (r)
owner → the class (Record)
The method always returns the string "system".
So:
Any access to the managed attribute will return "system" regardless of stored values.
3. Defining the Class That Uses the Descriptor
class Record:
status = Field()
A class named Record is defined.
The class attribute status is assigned an instance of Field.
This makes status a managed attribute controlled by the descriptor.
4. Creating an Instance of Record
r = Record()
An object r of class Record is created.
At this point:
r.__dict__ = {}
5. Manually Setting an Instance Attribute
r.__dict__["status"] = "user"
This directly inserts "status": "user" into the instance’s dictionary.
Now:
r.__dict__ = {"status": "user"}
6. Accessing r.status
print(r.status)
Here’s what Python does internally:
It sees r.status.
It checks the class Record and finds that status is a descriptor.
Descriptors take priority over instance dictionary values.
So Python calls:
Field.__get__(descriptor, r, Record)
__get__ returns "system".
So the instance value "user" is ignored.
7. Final Output
system
Final Answer
✔ Output:
system
.png)

0 Comments:
Post a Comment