How to give object away to python garbage collection?

前端 未结 4 796
走了就别回头了
走了就别回头了 2020-12-18 23:43

There are several threads on Python garbage collection in SO, and after reading about five, plus some doc on line, i am still not sure as to how garbage collection works and

4条回答
  •  伪装坚强ぢ
    2020-12-19 00:09

    None of this really has anything to do with garbage collection.

    Python's main method of memory management uses reference counting.

    In all cases above, Python keeps a count of all the references to the object, and when there are none left, the object is deleted (similar to std::shared_pointer in C++).

    References get decreased when

    1. the object holding them is either explicitly deleted (via del)
    2. or goes out of scope (see also here (esp. ex. 8)).

    In your case, this applies to either the john object, or either of the people containers. They go out of scope at the end of the function that created them (assuming they are not returned to the calling function). The vast majority of the time, you can just let them go out of scope - it's only when you create really heavy objects or collections - say inside a big loop - that you might want to consider explicitly using del.

    Garbage collection really only comes into play when there are reference cycles - for instance, when an object refers to itself. Like:

    a = []
    a.append(a)
    

    Again, this happens automatically, and you shouldn't need to do anything special.

提交回复
热议问题