Will objects continue to pile up in memory when creating objects within Python for?

Asked 2 years ago, Updated 2 years ago, 65 views

Rotate the for statement from the main.

The contents of the for statement create a class object A

for i in range(n):
    obj_A = make_obj_A()

The generated object A generates a myriad of other class objects B.

class make_obj():
    def __init__(self):
        for i in range(n):
            obj_B = make_obj_B()

In this case, this main process can be used once for is finished

Are we still storing a myriad of generated object Bs in memory?

What I want is that the first and last execution conditions (memory space) of the for statement are the same.

python memory

2022-09-22 19:37

1 Answers

First, Python uses garbage collection (reference counting) to clean up objects.

Naturally, when generated by iterations, the reference count is at least 1, so it is in memory.

"What I want is that the first and last execution conditions (memory space) of the for statement are the same" <- This cannot be done. If you continue to create an object and plan to use it, it must still exist in memory. If you don't need it, you can put it in a collection such as list and delete it explicitly when creating an object.


2022-09-22 19:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.