Code Explanation
import weakref
Imports the weakref module, which allows creating weak references and proxies to objects.
class A:
x = 10
Defines a class A with a class attribute x = 10.
This means any instance of A will have access to x.
obj = A()
Creates an instance obj of class A, which is a strong reference to the object.
Since obj is a strong reference, the object will not be garbage collected yet.
proxy = weakref.proxy(obj)
Creates a weak reference proxy proxy to obj using weakref.proxy(obj).
Unlike weakref.ref(), which requires calling (wref()),
a proxy behaves like the original object (i.e., proxy.x is the same as obj.x).
del obj
Deletes the strong reference obj.
Since there are no strong references left, the object is garbage collected.
The weak reference proxy (proxy) is now pointing to a deleted object.
print(proxy.x)
Now, proxy.x raises an error because obj no longer exists.
Since proxy is just a reference, it does not keep obj alive.
Accessing attributes of a deleted object causes a ReferenceError.
Final Output:
C: Raises ReferenceError
0 Comments:
Post a Comment