Local variables in classes and class instantiation

Matt Nordhoff mnordhoff at mattnordhoff.com
Sun Dec 23 05:49:49 EST 2007


A.J. Bonnema wrote:
> Hi all,
> 
> I just started using Python. I used to do some Java programming, so I am 
> not completely blank.
> 
> 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>
> .
> ----------------------------------------------------------------------
> Ran 3 tests in 0.001s
> 
> OK
> =============================================================== source
> The source of the test program is:
> 
> <snip>

What if the second object is separate, but just gets allocated at the
same location as the first one?

Try printing some unique attribute of each object, like the one that
stores the "cpuXX" argument that gets passed in.
-- 



More information about the Python-list mailing list