Local variables in classes and class instantiation

Peter Otten __peter__ at web.de
Sun Dec 23 06:05:18 EST 2007


A.J. Bonnema wrote:

> I have a small question about how classes get instantiated within other 
> classes. I have added the source of a test program to the bottom of this 
> mail, that contains 3 methods within a testclass that each instantiate 
> the same class and bind it to a local variable. My understanding was, 
> that the local variable gets garbage collected as soon as the method 
> goes out of scope. Thus I would expect the local variable 'cpu' in these 
> methods to be independant and create different instances of the class CPU.
> 
> Still, when I execute all three methods, I get two instances that are 
> equal and the third is different.
> Is there some circomstance that makes two object creations result in the 
> same object?
> 
> ============================================================= output
> Output from the (test)program is:
> cpu class = <cpu.CPU instance at 0x8244eec>
> .cpu class = <cpu.CPU instance at 0x8244eec>
> .cpu class = <cpu.CPU instance at 0x8244f0c>
> .

That two instances of CPU print the same "at 0x..." representation doesn't
mean they are the same object, they may just be located at the same
location in memory. For that to happen it is neccessary (but not
sufficient) for the first instance to be garbage-collected.

Peter



More information about the Python-list mailing list