Python Memory Management
This article is about how memory is managed within Python.
A Problem from Bloomberg Interview:
There is a class called Car, and a function called create_car to create and return an instance, where do we store the instance? When it’s returned and assigned to a variable, where is the variable?
class Car(): def __init__(self): doors = 5 seats = 4 def create_car(): benz = Car() print(hex(id(benz))) return benz my_benz = create_car() print(hex(id(my_benz)))
As we can see, the memory addresses are the same. Benz is a variable (instance) that was created in the Heap, and Benz is a reference to that instance, when the function finished, the reference is returned and assigned to my_benz. So my_benz should still be a reference to the instance that we created.
Three Mechanisms in Python Memory Management:
(1) Garbage Recycle
(2) Reference Counter
(3) Memory Layers
Memory Management in Python: https://realpython.com/python-memory-management/