Really, Really Confused...
Ben Mitchell
ben at semio.com
Wed Dec 6 20:49:38 EST 2000
Hi Folks,
I've encountered a very strange problem that'll take a little space to
explain. I hope some of you will brave your way to the end though because
I'm well and truly stumped by this one.
First some history: I got started on the road to confusion because I was
trying to turn my Python class into a COM server, though the issue I
ultimately ran into has nothing to do with COM. It looks like the VB app I
was using to test the COM server i holding a long running reference to the
COM object, and then calling __init__ to initialize it instead of recreating
it from scratch when I "create" it. I don't know enough VB/COM to know why
this would be the case, but whatever - the init function was being invoked
repeatedly and it was causing problems. I decided to remove some complexity
and just reinvoke the initializer a second time from the basic script to
debug. I have since been able to reduce the issue down to the following
snippet of code:
class cApp:
object = None
def __init__(self):
self.object = None
self.object = cObject()
class cObject:
myDict = {}
def __init__(self):
if self.myDict.has_key("foo"):
raise "Already set"
self.myDict["foo"] = "some value"
testApp = cApp()
testApp.__init__()
print "Finished"
When the init function runs the second time, the "Already set" exception is
raised. Now I really don't understand why this would be. When
cApp.__init__() is invoked, it releases its reference to self.object before
creating a new one (self.object = None). As best I'm aware, it then creates
a completely new cObject with no common references to the old one. In what
conceivable way could the myDict of the new cObject have a value already set
for "foo"?
And now it gets more interesting. If I substitute a string in place of a
dict as the value in cObject, everything works fine:
class cApp:
object = None
def __init__(self):
self.object = None
self.object = cObject()
class cObject:
myString = None
def __init__(self):
if self.myString != None:
raise "Already set"
self.myString = "some value"
testApp = cApp()
testApp.__init__()
print "Finished"
This runs to completion without griping. HOW IS THIS DIFFERENT?
I think the real root of my confusion is that I don't understand what the
constructor is doing here. Why is it that when I create a seemingly new
cObject, it has any value at all stored within it?
Thanks for reading all this, and thanks in advance for your help.
Best,
-Ben
More information about the Python-list
mailing list