DanishAnsari09
DanishAnsari09

Reputation: 23

Destructor in Python

Below is the code. I did not manually del object reference but then also in VScode __del__ gets invoked. But the same piece of code is working in Jupyter Notebook. This means, __del__ is not called automatically. Is there any problem with the code? Confused. Does VScode handle Garbage Collector (automatically)? Googled a lot, but did not get an appropriate answer.

class Student:
    # constructor
    def __init__(self, name):
        print('Inside Constructor')
        self.name = name
        print('Object initialized')

    def show(self):
        print('Hello, my name is', self.name)

    # destructor
    def __del__(self):
        print('Inside destructor')
        print('Object destroyed')

# create object
s1 = Student('Emma')
s2 = s1;
s3 = s1;
print("Id of S1: " , id(s1));

Upvotes: 1

Views: 1005

Answers (1)

S.B
S.B

Reputation: 16476

It's better to call __del__ a finalizer method because this method gets called exactly when the object is about to be garbage collected. (like when all references to that object are gone.)

In VSCode or even when you run your script in terminal, when the interpreter reaches the end of the file it will terminate the execution and the process, therefore any objects will be destroyed. So you can see that this method gets called. So even if you didn't del the references to the object explicitly, all the references will be gone at the end.

Jupyter notebook on the other hand is still running, and also maybe it keeps a reference to your object for internal works...

Put a simple input() in the last line of your code, you can see that the __del__ wont get called in VScode or terminal as well.

Upvotes: 3

Related Questions