DBWeinstein
DBWeinstein

Reputation: 9479

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?

Upvotes: 4

Views: 233

Answers (7)

brandizzi
brandizzi

Reputation: 27050

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.

Upvotes: 13

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

1st foo = Foo():

it creates a new instance object and assigns it to foo, see foo is just a reference to the object returned by Foo()

2nd foo = Foo()

it creates a new instance object and assigns it to foo, and the previous instance object Foo() is garbage collected as there's no variable pointing to it.

example:

>>> class Foo:
...   pass
... 
>>> 
>>> foo=Foo()  
>>> id(foo)   #foo points to an object with id 3077166220L
3077166220L
>>> foo=Foo()  #now foo points to some other object and the object with id 3077166220L is garbage collected
>>> id(foo)
3077166252L  
>>> 
>>> 
>>> temp=foo      #now both foo and temp point to same object i.e 3077166252L  
>>> foo=Foo()     #assign foo to a new object
>>> id(temp)      #temp still points 3077166252L ,so it's not garbage collected   
3077166252L 
>>> id(foo)       #it points to a new object   
3077166092L       

Upvotes: 2

Rajesh J Advani
Rajesh J Advani

Reputation: 5710

A couple of points to note.

  1. The name 'foo' is a variable defined in your code. In Python, the variable doesn't have a type until you assign it a value.
  2. When you say foo = Foo() you're assigning your variable foo the instance of an object of type Foo. Foo() creates this instance by calling the constructor of the Foo class without any parameters.
  3. Each call to Foo() creates a new instance. Hence, repeating foo = Foo() in your code will create multiple instances of the Foo class, and assign them to the variable foo. Earlier instances that were pointed to by the foo variable will no longer have a reference and can be garbage collected (assuming you didn't assign any other references to those instances in the meanwhile).

Hence, the words you use to describe your question

create second instance of a class with the same name as the existing instance

are actually not right. Because you are not creating another instance "with the same name". You are creating another instance, and assigning it to "the same variable".

Upvotes: 1

Thomas Orozco
Thomas Orozco

Reputation: 55197

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

Upvotes: 5

Max
Max

Reputation: 10985

The second one will override the first. (It takes the place of the name in the module's globals dictionary, where all global variables, functions, and classes are stored).

However, the foo = Foo() that you created will continue to use the original implementation from when it was created, until you make a new foo = Foo().

Upvotes: 0

AI Generated Response
AI Generated Response

Reputation: 8835

You end up binding a new Foo object to foo and your old Foo object will lose a reference. If an object does not have any references, then it will be collected on the next garbage collection.

Upvotes: 0

behnam
behnam

Reputation: 1979

  1. There's no overwrite in Python.
  2. When you write Foo() a new instance is created (class method __new__ and instance method __init__ are called, in order)
  3. When there's no pointer to an instance of a class, Python's Garbage Collector will eventually delete that instance (and instance method __del__ is called on that instance)

Upvotes: 0

Related Questions