I’m not sure how to ask the question other than by example.
Lets say I have a class:
class Foo():
pass
and I create an instance of it:
foo = Foo()
...
then, as part of my program, I recreate the same instance with the same name (to restart a game but keeping a score total in yet another, separate class called Bar).
foo = Foo()
...
(I don’t know the correct terminology) I havent written any code to eliminate the first instance. Is the first instance eliminated or overwritten? It seems to work for a small program. If I do it many times am I going to run into trouble?
Let me try to explain it graphically.
When you do
for the first time, you are creating an object of type
Fooin memory (withFoo()) and, at the same time, creating a variable which will point to this object:When you execute
for the second time, you are creating another object. Meanwhile, you are taking the same variable and pointing it to the new object. Of course, the variable will not point to the previous object anymore:
Now, what happens to the first object? Well, if there is no other variable in your program pointing to it, it is useless, since you cannot access it anymore! In this case, the object will be destroyed/freed from the memory when the interpreter runs the garbage collector. The garbage collector is an algorithm which will look for every object which is not accessible and will remove it. The garbage collector does not run every time, so it can take a time to the object be destroyed.
So, in your scenario, what happens is: