Dynamic property names on class

Bryan bryanvick at gmail.com
Fri Nov 13 11:59:54 EST 2009


I have several properties on a class that have very similar behavior.
If one of the properties is set, all the other properties need to be
set to None.  So I wanted to create these properties in a loop like:

class Test(object):
	for prop in ['foo', 'bar', 'spam']:
		# Attribute that data is actually stored in
		field = '_' + prop
		# Create getter/setter
		def _get(self):
			return getattr(self, field)
		def _set(self, val):
			setattr(self, field, val)
			for otherProp in prop:
				if otherProp != prop: setattr(self, '_' + otherProp, None)
		# Assign property to class
		setattr(Test, prop, property(_get, _set))

t = Test()
t.foo = 1
assert t.bar == t.spam == None

But the class Test is not defined yet, so I can't set a property on
it.  How can I do this?



More information about the Python-list mailing list