Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python destructing two objects when (I think) I only destructed one

I am learning Python and decided to create a simple class to help me understand. The class is for Tennis Balls.
I have a class attribute of num_balls, and instance attributes of serial_number and age.

I create two instances of the TennisBall class and name them ‘a’ and ‘b’. When I call the destructor for ‘a’, instance ‘b’ also gets destructed.

class TennisBall:
    ball_count = 0    
    
    def __init__(self, serial_number, age):
        self.serial_number = serial_number
        self.age = age
        print("New Tennis Ball created {}!".format(self.serial_number))
        TennisBall.ball_count +=1
        
    def __del__(self):
        print("Tennis ball {} has been deleted :(".format(self.serial_number))
        TennisBall.ball_count -= 1
        
        
        

a = TennisBall(1234, 0)
print("Num balls: {} ".format(TennisBall.ball_count))

b = TennisBall(2345, 0)
print("Num balls: {} ".format(TennisBall.ball_count))

del a
print("Num balls after del ball a: {} ".format(TennisBall.ball_count))

I destructed instance ‘a’ and it was deleted as expected. However, instance ‘b’ was also destructed, even though I did not call that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried destructing ‘b’ instead and again both ‘a’ and ‘b’ were destructed.

>Solution :

This is expected behavior.

When a program terminates, all objects remaining in its memory are deleted (which means that their destructors will be called).

When I run the program, the print statement for Tennis ball 2345 has been deleted :( is executed after the print statement for Num balls after del ball a: 1. In other words, the destructor for ball b is called when the program terminates, after all the code has been executed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading