Mark attribute as read-only

Steven Bethard steven.bethard at gmail.com
Wed Mar 16 17:59:53 CET 2005


Florian Lindner wrote:
> how can I mark a attribute of a class as read-only (for non classmembers)?
> Yes, stupid question, but the docu gave me no help.

Declare it as such in the documentation. ;)

If you want to provide error messages, you could alternatively define a 
property:

py> class C(object):
...     def _getx(self):
...         return self._x
...     x = property(fget=_getx)
...     def __init__(self, x):
...         self._x = x
...
py> c = C(4)
py> c.x
4
py> c.x = 6
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
AttributeError: can't set attribute

STeVe



More information about the Python-list mailing list