Code Explanation:
1. Define the Descriptor Class
class D:
A class named D is created.
This class acts as a descriptor because it defines the special method:
__get__()
A descriptor can control what happens when an attribute is accessed.
2. Define __set_name__()
def __set_name__(self, owner, name):
__set_name__() is automatically called by Python when the descriptor is assigned to a class attribute during class creation.
Here:
self → the D object
owner → the class containing the descriptor
name → the attribute name used for the descriptor
Later, when Python creates class A:
class A:
value = D()
Python effectively calls:
D_object.__set_name__(A, "value")
3. Store the Attribute Name
self.name = name
The value of name is:
"value"
Therefore:
self.name = "value"
The descriptor now remembers the name under which it was assigned.
Conceptually:
D object
└── name = "value"
4. Define __get__()
def __get__(self, obj, owner):
__get__() controls what happens when the descriptor is accessed.
Here, the method receives:
self → descriptor object
obj → instance being accessed, or None when accessed through the class
owner → the class that owns the descriptor
5. Return the Formatted String
return f"{owner.__name__}:{self.name}"
This creates a string using two values.
owner.__name__
The owner is class A.
Therefore:
owner.__name__ → "A"
self.name
Earlier, __set_name__() stored:
self.name → "value"
Therefore the expression becomes:
"A" + ":" + "value"
Result:
"A:value"
6. Define Class A
class A:
value = D()
A D object is created:
D()
and assigned to:
A.value
During class creation, Python automatically calls:
__set_name__(A, "value")
So internally the descriptor stores:
name = "value"
7. Access A.value
print(A.value)
This is where the descriptor becomes important.
Because value is a descriptor, accessing:
A.value
invokes:
D.__get__(self, None, A)
Notice that obj is None because we are accessing the attribute through the class, not through an instance.
The important value is:
owner = A
8. Build the Final Value
Inside __get__():
f"{owner.__name__}:{self.name}"
becomes:
f"{'A'}:{'value'}"
which produces:
"A:value"

0 Comments:
Post a Comment