Code Explanation:
1. Defining the descriptor class
class D:
This defines a class named D.
Objects of this class will act as descriptors.
2. Implementing __get__
def __get__(self, obj, owner):
return "desc"
__get__ makes D a descriptor.
Parameters:
self → the descriptor object (D()).
obj → the instance accessing the attribute (c).
owner → the class (C).
Whenever this descriptor is accessed, it returns the string "desc".
Since only __get__ is defined, this is a non-data descriptor.
3. Defining the owner class
class C:
This defines a class named C.
4. Assigning the descriptor to a class attribute
x = D()
x is a class attribute.
It is controlled by the descriptor D.
5. Creating an instance
c = C()
An object c of class C is created.
At this point, c has no instance attributes.
6. Manually adding an instance attribute
c.__dict__['x'] = "inst"
This inserts an instance attribute named x with value "inst".
It directly modifies the instance’s attribute dictionary.
7. Accessing the attribute
print(c.x)
๐ Attribute lookup order in this case:
Data descriptors
Instance attributes
Non-data descriptors
Class attributes
D is a non-data descriptor.
Python finds x in c.__dict__ first.
The descriptor’s __get__ method is not called.
✅ Final Output
inst

0 Comments:
Post a Comment