Code Explanation:
1) import weakref
Imports Python’s weakref module.
A weak reference allows referencing an object without increasing its reference count.
That means the object can still be garbage-collected even if a weak reference to it exists.
2) class A: pass
Defines an empty class A.
It doesn’t have any methods or attributes.
3) a = A()
Creates an instance of class A.
Variable a holds a strong reference to this object.
4) r = weakref.ref(a)
Creates a weak reference to the object a.
r is not the object itself, but a callable reference.
To access the object, you must call r().
5) print(r() is a)
Calls r() → returns the actual object being referenced (same as a).
At this point, a still exists, so r() is the same object.
Output: True.
6) del a
Deletes the strong reference a.
Now the object has no strong references.
Since only a weak reference remains, the object becomes eligible for garbage collection.
7) print(r() is None)
Calls r() again.
The object was garbage-collected after del a.
So r() now returns None.
Output: True.
Final Output
True
True
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment