Read-only attributes using properties?

James T. Dennis jadestar at idiom.com
Tue Dec 17 20:04:29 EST 2002


Pedro RODRIGUEZ <pedro_rodriguez at club-internet.fr> wrote:
> 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

 Try: 
 
 class TProp(object):
    def __init__(self):
        self.__dict__[a] = 0

 instead?



More information about the Python-list mailing list