Read-only attributes using properties?

Pedro RODRIGUEZ pedro_rodriguez at club-internet.fr
Thu Nov 21 09:06:04 EST 2002


On Thu, 21 Nov 2002 14:27:55 +0100, Roberto Amorim wrote:

> 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
 
Just my guess, but in your example you expect 'a' to be an attribute
AND a property. AFAIK, the examples on property make a clear distinction
between both of them naming the attribute '_a' (for internal use of the
class only), and property 'a' as the public interface to it.

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

$ ./local/bin/python2.2 z.py
0
Traceback (most recent call last):
  File "z.py", line 15, in ?
    t.a = 5
  File "z.py", line 10, in set_a
    raise MyException
__main__.MyException


HTH,
Pedro



More information about the Python-list mailing list