Code Explanation:
1. Defining the Descriptor Class
class Tracker:
Tracker is a descriptor because it implements the __get__ method.
It will control access to an attribute when used inside another class.
2. Class-Level Shared State
total = 0
total is a class variable of Tracker.
It is shared across all instances and all owners.
3. Implementing __get__
def __get__(self, obj, owner):
Tracker.total += 1
obj.local = getattr(obj, "local", 0) + 1
return obj.local, Tracker.total
What happens when x is accessed:
Tracker.total is incremented → counts total accesses across all objects.
obj.local is incremented → counts accesses for that specific object.
Returns a tuple (obj.local, Tracker.total).
4. Defining the Owner Class
class A:
x = Tracker()
x is now a managed attribute controlled by the Tracker descriptor.
5. Creating Two Instances
a = A()
b = A()
Two separate objects of class A are created.
6. Evaluating the Print Statement
print(a.x, b.x, a.x)
This evaluates from left to right.
▶ First access: a.x
Tracker.total becomes 1.
a.local becomes 1.
Returns (1, 1).
▶ Second access: b.x
Tracker.total becomes 2.
b.local becomes 1.
Returns (1, 2).
▶ Third access: a.x again
Tracker.total becomes 3.
a.local becomes 2.
Returns (2, 3).
7. Final Output
(1, 1) (1, 2) (2, 3)


0 Comments:
Post a Comment