简体   繁体   中英

How can i delete objects in python3.*

I am writing a binary tree class. And i would like to delete the whole tree (all nodes in it) So i want to understand how to delete objects in python.

I have function del_obj(obj). I pass there "a" and it doesn't work correctly. As i suppose, it is copy of "a". But id method shows the same id. I am confused.

def del_obj(obj):                                                               
   print(id(obj)) # 111                                                              
   del obj                                                                     

a = 3                                                                           
print(id(a)) # 111                                                                    
del_obj(a)
print(a) # 3  

In Python, del doesn't delete an object , it deletes a name . The object will only get deleted when it cannot be reached from any name anymore.

Once the root of the tree cannot be reached from any name, all the other nodes in the tree which could only be reached from a name that is associated with that root object will themselves become unreachable, and all the nodes will get deleted, unless someone has another name somewhere that is pointing at one of them.

(If you have a cycle of names then that still should all be cleaned up, but the CPython implementation has a few gotchas in this case. But since you describe the data structure as a tree, this probably doesn't apply to your situation.)

I would recommend you read the classic article Facts and myths about Python names and values .

You need to say del a in the outer scope. Your del_obj function doesn't work because it only deletes its own reference, which doesn't affect the code outside that function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM