When is del useful in python?

前端 未结 21 2232
野趣味
野趣味 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:17

    I would like to elaborate on the accepted answer to highlight the nuance between setting a variable to None versus removing it with del:

    Given the variable foo = 'bar', and the following function definition:

    def test_var(var):
        if var:
            print('variable tested true')
        else:
            print('variable tested false')
    

    Once initially declared, test_var(foo) yields variable tested true as expected.

    Now try:

    foo = None
    test_var(foo)
    

    which yields variable tested false.

    Contrast this behavior with:

    del foo
    test_var(foo)
    

    which now raises NameError: name 'foo' is not defined.

提交回复
热议问题