13

Why I can not delete a class instance in python

 3 years ago
source link: https://www.codesd.com/item/why-i-can-not-delete-a-class-instance-in-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Why I can not delete a class instance in python

advertisements

I want to delete a class instance or make it None in python. But I'm not able to do it. In general my code does something as follows:-

class Foo:
  pass

f = Foo()
g = Foo()
f.attr = g
h = f.attr
del h
print f.attr  # This is not None but it should be right?

More specifically this problem came while implementing binary search trees in python. My delete function does something like this:-

class Tree:
  def delete(self, key):
    min_right = self.right.getmin()
    self.key = min_right.key
    del min_right  # Does not work

Am I doing something wrong or is it expected behavior? If it is expected, what is the best way by OOP standards to achieve what I am trying to do?


You have a situation that looks like this:

                  g

                  |

     <__main__.Foo object at 0x...>

          /               \

       f.attr               h

i.e. three references to the same underlying object. All that del h does is remove the name h, like this:

                  g

                  |

     <__main__.Foo object at 0x...>

          /               

       f.attr

The underlying object doesn't change, and the two other names still provide a reference to it, all you've done is remove one reference to the Foo instance. h is now a NameError, but g and f.attr will work just fine.

 # This is not None but it should be right?

I don't know why you would conclude that - if you did succeed in breaking the reference from f.attr to the Foo instance, you would get an AttributeError, not None.

Recommended reading on Python names: http://nedbatchelder.com/text/names.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK