Python Memory Management
This article is about how memory is managed within Python.
TODO : https://realpython.com/python-memory-management/
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?
Source Code:
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)))
Output:
0x100d60c88 0x100d60c88
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
Reference
Memory Management in Python: https://realpython.com/python-memory-management/