When is del useful in python?

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

    Yet another niche usage: In pyroot with ROOT5 or ROOT6, "del" may be useful to remove a python object that referred to a no-longer existing C++ object. This allows the dynamic lookup of pyroot to find an identically-named C++ object and bind it to the python name. So you can have a scenario such as:

    import ROOT as R
    input_file = R.TFile('inputs/___my_file_name___.root')
    tree = input_file.Get('r')
    tree.Draw('hy>>hh(10,0,5)')
    R.gPad.Close()
    R.hy # shows that hy is still available. It can even be redrawn at this stage.
    tree.Draw('hy>>hh(3,0,3)') # overwrites the C++ object in ROOT's namespace
    R.hy # shows that R.hy is None, since the C++ object it pointed to is gone
    del R.hy
    R.hy # now finds the new C++ object
    

    Hopefully, this niche will be closed with ROOT7's saner object management.

提交回复
热议问题