27. Python's Garbage Collection
1. Manually Triggering 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 collection2. Reference Counting
import 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 deletion3. Cyclic References
4. Disabling Garbage Collection
5. Tracking Unreachable Objects
6. Weak References
7. Customizing Object Finalization with __del__
__del__8. Memory Management with Generations
9. Viewing Objects in Garbage
10. Memory Management with id and del
id and delLast updated