when does python delete variables?

前端 未结 4 1588
借酒劲吻你
借酒劲吻你 2020-12-14 22:15

I know that python has an automatic garbage collector and so it should automatically delete variables when there are no more reference to them.

My impression is tha

4条回答
  •  春和景丽
    2020-12-14 22:45

    Implementations use reference counting to determine when a variable should be deleted.

    After the variable goes out of scope (as in your example) if there are no remaining references to it, then the memory will be freed.

    def a():
        x = 5 # x is within scope while the function is being executed
        print x
    
    a()
    # x is now out of scope, has no references and can now be deleted
    

    Aside from dictionary keys and elements in lists, there's usually very little reason to manually delete variables in Python.

    Though, as said in the answers to this question, using del can be useful to show intent.

提交回复
热议问题