Read-only attributes using properties?

Roberto Amorim wolfoxbr at hotmail.com
Thu Nov 21 08:27:55 EST 2002


I was thinking about trying to use the new properties on Python 2.2 to
implement read-only attributes. So I tried the following:

class MyException(Exception):
	pass

class TProp(object):
	def __init__(self):
		self.a = 0
	def get_a(self):
		return self.a
	def set_a(self, v):
		raise MyException
	a = property(get_a, set_a, None, "Test a")

t = TProp()
print t.a
t.a = 5

I was expecting that the script would fail with an exception on the
"t.a = 5" command. However, I was surprised to see the code fail on
the attribution inside __init__ - that is, there is no "inner class
scope", or direct access within the class itself, and no clear way to
initialize the property. If the property is an alias to the real
internal variable (call it size, for instance), it works, but then if
I try to add a __slots__ list excluding the internal var and only
adding the external reference (__slots__=("a")) it stops working
again.

Is there any other way to do that?

Thanks in advance,

Roberto



More information about the Python-list mailing list