How Does Python Memory Management Work?

后端 未结 5 1357
耶瑟儿~
耶瑟儿~ 2020-12-23 22:22

Okay, I got this concept of a class that would allow other classes to import classes on as basis versus if you use it you must import it. How would I go about implementing i

5条回答
  •  难免孤独
    2020-12-23 22:35

    Python -- like C#, Java, Perl, Ruby, Lua and many other languages -- uses garbage collection rather than manual memory management. You just freely create objects and the language's memory manager periodically (or when you specifically direct it to) looks for any objects that are no longer referenced by your program.

    So if you want to hold on to an object, just hold a reference to it. If you want the object to be freed (eventually) remove any references to it.

    def foo(names):
      for name in names:
        print name
    
    foo(["Eric", "Ernie", "Bert"])
    foo(["Guthtrie", "Eddie", "Al"])
    

    Each of these calls to foo creates a Python list object initialized with three values. For the duration of the foo call they are referenced by the variable names, but as soon as that function exits no variable is holding a reference to them and they are fair game for the garbage collector to delete.

提交回复
热议问题