Python class strangeitude

Tom Hanks garbagecollector86 at hotmail.com
Mon Aug 26 03:10:06 CEST 2002


"Mr. Neutron" <nicktsocanos at charter.net> wrote
> Hi,
> 	I have discovered a strange thing about Python. I have a class, we'll
> call it MyClass. MyClass is derived from MyClassBase.
> 
> Now I do this
> 
> Jimmy = MyClass(...)
> ...
> 
> Randy = MyClass(...)
> 
> 
> And guess what? Jimmy and Randy are the same darn thing in memory! I was
> assuming that classes in Python were like in C++ in the way they behave.
> 
> Now, if I want to create two distinct objects Jimmy and Randy, is there
> anyway to do this in Python from the same class? It lacks the new
> statement, so I do not know how to tell Python to create a new object in
> memory with it's own variables and everything.
> 
> I can prove it to you if you don't believe me! Variables in Jimmy are
> Variables in Randy! Whatever I do to Randy, happens to Jimmy. They are
> exactly the same Object in memory.

As others have said, we can't be sure what is happening in your program 
with this partial example. I'll hazard a guess that might help you... 
it sounds like you could be using class variables (think static members
in C++ if that is familiar to you), rather than instance variables. I 
hope the following code snippet is informative for someone

>>> class MyClass():
...	var1 = 1                # all instances share var1
...	def __init__(self): 
...		self.var2 = 1   # each instance has its own var2



More information about the Python-list mailing list