When should an attribute be private and made a read-only property? [closed]

Just my two cents, Silas Ray is on the right track, however I felt like adding an example. 😉

Python is a type-unsafe language and thus you’ll always have to trust the users of your code to use the code like a reasonable (sensible) person.

Per PEP 8:

Use one leading underscore only for non-public methods and instance variables.

To have a ‘read-only’ property in a class you can make use of the @property decoration, you’ll need to inherit from object when you do so to make use of the new-style classes.

Example:

>>> class A(object):
...     def __init__(self, a):
...         self._a = a
...
...     @property
...     def a(self):
...         return self._a
... 
>>> a = A('test')
>>> a.a
'test'
>>> a.a="pleh"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

Leave a Comment