trap setting attribute when the attribute is dict

yosuke at ccwf.cc.utexas.edu yosuke at ccwf.cc.utexas.edu
Mon Sep 3 14:00:08 EDT 2007


Hello all,

I have a question which might be simple or need some work around.

I want to do something like this.  My class/instance has a dict as a
property.  I want the instance to catch the change in the dict (change
in some values, addition/deletion of key/value etc) to be recognized by
the class instance.  

How can I do this?  Any suggestions are very well appreciated.



Here is an example of what I want my class to behave:

class test(object):
	def __init__(self):
		self._d = {}
		self._changed = False
	def getd(self):
		print 'called getd'
		return self._d
	# dont know what to do next
	def setd(self,val):
		print 'called setd', key, val
		self._d[key] = val
		self._changed = True
	d = property(getd,setd,None,None)

	def getc(self):
		return self._changed
	changed = property(getc,None,None,None)

if __name__ == '__main__':
	obj = test()
	print 'obj.changed = ', obj.changed
	print

	# I want obj to know that its propety d being changed here
	print "t.d['a'] = 1"
	obj.d['a'] = 1
	print

	# I want the "changed" property to be True
	print 'obj.changed = ', obj.changed









-- 
yosuke kimura
Center for Energy and Environmental Resources
The Univ. of Texas at Austin, USA



More information about the Python-list mailing list