Really, Really Confused...

Damjan arhiv at freemail.org.mk
Thu Dec 7 13:53:19 CET 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:
	myDict={}
	def __init__(self):
		if self.myDict.has_key('foo'):
			raise 'Already set'
		self.myDict['foo']='bar'

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

a1=A()
a2=A()
b1=B()
b2=B()

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
'B.myString'.

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'}	
c1=C()

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

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




More information about the Python-list mailing list