When is del useful in python?

前端 未结 21 2253
野趣味
野趣味 2020-11-22 11:58

I can\'t really think of any reason why python needs the del keyword (and most languages seem to not have a similar keyword). For instance, rather than deletin

21条回答
  •  误落风尘
    2020-11-22 12:13

    To add a few points to above answers: del x

    Definition of x indicates r -> o (a reference r pointing to an object o) but del x changes r rather than o. It is an operation on the reference (pointer) to object rather than the object associated with x. Distinguishing between r and o is key here.

    • It removes it from locals().
    • Removes it from globals() if x belongs there.
    • Removes it from the stack frame (removes the reference physically from it, but the object itself resides in object pool and not in the stack frame).
    • Removes it from the current scope. It is very useful to limit the span of definition of a local variable, which otherwise can cause problems.
    • It is more about declaration of the name rather than definition of content.
    • It affects where x belongs to, not where x points to. The only physical change in memory is this. For example if x is in a dictionary or list, it (as a reference) is removed from there(and not necessarily from the object pool). In this example, the dictionary it belongs is the stack frame (locals()), which overlaps with globals().

提交回复
热议问题