Clear variable in python

后端 未结 7 1383
猫巷女王i
猫巷女王i 2020-12-22 17:16

Is there a way to clear the value of a variable in python?

For example if I was implementing a binary tree:

Class Node:
    self.left = somenode1
            


        
相关标签:
7条回答
  • 2020-12-22 17:52

    The del keyword would do.

    >>> a=1
    >>> a
    1
    >>> del a
    >>> a
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'a' is not defined
    

    But in this case I vote for self.left = None

    0 讨论(0)
  • 2020-12-22 17:53
    • If want to totally delete it use del:

      del your_variable

    • Or otherwise, to Make the value None:

      your_variable = None

    • If it's an iterable (such as a list or tuple), you can make it empty like:

      your_variable.clear()

    Then your_variable will be empty

    0 讨论(0)
  • 2020-12-22 17:58

    What's wrong with self.left = None?

    0 讨论(0)
  • 2020-12-22 18:04

    var = None "clears the value", setting the value of the variable to "null" like value of "None", however the pointer to the variable remains.

    del var removes the definition for the variable totally.

    In case you want to use the variable later, e.g. set a new value for it, i.e. retain the variable, None would be better.

    0 讨论(0)
  • 2020-12-22 18:06

    Actually, that does not delete the variable/property. All it will do is set its value to None, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

    del self.left
    
    0 讨论(0)
  • 2020-12-22 18:08

    Do you want to delete a variable, don't you?

    ok, I think I've got a best alternative idea to @bnul answer:

    You can delete individual names with del:

    del x or you can remove them from the globals() object:

    for name in dir(): if not name.startswith('_'): del globals()[name]

    This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

    Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

    Please reconsider this answer!

    0 讨论(0)
提交回复
热议问题