Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I attribute a second instance of a class with the same variable holding an existing instance?

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?

like image 473
DBWeinstein Avatar asked Nov 30 '22 14:11

DBWeinstein


2 Answers

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:

enter image description here

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:

enter image description here

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 reference to the first object is overwritten, but the object will exist. If another variable points to it, it will not be destroyed.
  • However, if there is no other variable pointing to it, the object will be eliminated at some point in the future.
like image 175
brandizzi Avatar answered Dec 06 '22 18:12

brandizzi


The basic (and probably sufficient) answer:

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.

A relevant detail: the Singleton pattern

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
like image 33
Thomas Orozco Avatar answered Dec 06 '22 19:12

Thomas Orozco