0

I'm really confused by the following code's output, that I am running on Ipython Notebook:

class Point(object):

   def __init(self, x=0, y=0):
      self.x = x
      self.y = y

   def __del__(self):
      class_name = self.__class__.__name__
      print class_name, "destroyed"

pt1 = Point()
pt2 = pt1

The output is as follows and I can't seem to understand when the destructor is called: Point destroyed

Also, then when I write the code below and expect to get an Error, I don't.

del pt1 
del pt2

Thanks

Edit: I understand that Python only calls _del_() when the reference count goes to 0, but what I don't understand is why writing the following results in the Output: Point destroyed.

pt1 = Point()
pt2 = pt1

Also, given the above, I know that either pt1 or pt2 doesn't exist and would thus expect an error in the below code, but that doesn't happen.

del pt1
del pt2
3
  • why do you expect an error? Commented Oct 1, 2014 at 20:39
  • @PadraicCunningham I've edited the question, which explains why I think there is an Error. I'm quite confused. Commented Oct 1, 2014 at 20:50
  • pt1 = Point()pt2 = pt1 should not output anything Commented Oct 1, 2014 at 20:52

2 Answers 2

2

I would assume there is something regarding reference counting going on when multiple variables point to the same object. Look at the below example.

L1 = [1,2,3]
L2 = L1

Now let's look at our ids

>>> id(L1)
49127672

>>> id(L2)
49127672

So they point to the same list as expected.

del L1

>>> L2
[1, 2, 3]

>>> id(L2)
49127672

L2 still exists and still has the same id, even though L1 was deleted, which created the object in the first place.

So long story short, I think Python uses reference counting, and does not actually delete the object until the reference count drops to 0.

Regarding your edit

del pt1    # Reference count dropped from 2 to 1, __del__ is NOT called
del pt2    # Reference count dropped from 1 to 0, __del__ called

Note the output message "Point destroyed" is called because of del pt2, because pt1 does not invoke this.

Sign up to request clarification or add additional context in comments.

Comments

0

as docs say:

Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block. If the name is unbound, a NameError exception will be raised.

so you just remove two entries from local namespace, with each removal decreasing reference count by one. Only after ref count goes to zero, __del__ is called. That's not C ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.