27. Python's Garbage Collection
import gc
class Demo:
def __del__(self):
print("Object destroyed.")
obj = Demo()
del obj # Object eligible for garbage collection
gc.collect() # Manually trigger garbage collectionimport sys
class Demo:
pass
obj = Demo()
print(sys.getrefcount(obj)) # Get reference count
ref = obj
print(sys.getrefcount(obj)) # Reference count increases with another reference
del ref
print(sys.getrefcount(obj)) # Reference count decreases after deletionLast updated