Really, Really Confused...

Damjan arhiv at
Thu Dec 7 07:53:19 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.

Let's simplify your examples:

class A:
	def __init__(self):
		if self.myDict.has_key('foo'):
			raise 'Already set'

class B:
	def __init__(self):
		if self.myString != None
			raise 'Already set'
		self.myString = 'bar'


Here is what happens. 

'myDict', in Class A, is a Class wide dictionary (so called 'static' in some
languages). It's created when the class is defined, and here it can be 
accessed through either of 'A.myDict' or 'a1.myDict', it's the same object.

'myString' = None, also creates a Class wide None object, and that object is
accesed in the 'if self.myString...' statement. But later a string object is
created ('bar') and referenced to 'self.myString'. Now, 'self.myString' hides

Check this:
While 'a1.myDict', 'a2.myDict' and 'A.myDict' is the same object, 
'b1.myString', 'b2.myString' and 'B.myString' are diferent objects 
(only two of them actually being strings).

Perhaps, what you needed was this:

class C:
	myDict = {}
	def __init__(self):
		# create a new dictionary object and
		# reference it to self.myDict
		self.myDict = {'foo':'bar'}	

Now, 'C.myDict' and 'c1.myDict' are diferent objects.

Damjan Georgievski		|           Дамјан Георгиевски
Skopje, Macedonia		|           Скопје, Македонија

More information about the Python-list mailing list