Read-only attributes using properties?
Inyeol Lee
inyeol.lee at siimage.com
Wed Dec 18 13:58:14 EST 2002
More information about the Python-list mailing list
Wed Dec 18 13:58:14 EST 2002
- Previous message (by thread): Read-only attributes using properties?
- Next message (by thread): Python Babushka?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Wed, Dec 18, 2002 at 01:04:29AM -0000, James T. Dennis wrote: > 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? > -- > http://mail.python.org/mailman/listinfo/python-list Common idiom is to separate public read-only attribute 'a' and private storage attribute '_a'. 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") HTH, Inyeol Lee...
- Previous message (by thread): Read-only attributes using properties?
- Next message (by thread): Python Babushka?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list