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
foo = Foo()
for the first time, you are creating an object of type Foo
in memory (with Foo()
) and, at the same time, creating a variable which will point to this object:
When you execute
foo = Foo()
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:
The variable foo
is assigned to a new instance, which knows nothing of the former one.
It's basically going to be the same as:
a = 1
a = 2
At some point (probably sooner than later), the old instance of foo
will be garbage collected (unless you still have references to it somewhere else).
The easy way to understand this is that the foo
name is just a pointer that points to an actual object. If you have foo
point at a new object, then foo
points at a new object, period.
There are design patterns (the singleton
one comes to mind), which may change this behavior.
Basically, the Foo.__new__
classmethod is the one which decides what you're going to get when you do Foo()
.
This method could be built so that it always return the first instance that you created, but that's sightly off-topic.
Here's a sample implementation:
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(cls, *args, **kwargs)
return cls._instance
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With