The Python built-in function property can be used as a decorator to create read-only attributes of a class, as described in the Python documentation for built-in functions. To make a property read-only, simply do not define a setter method for that property, in which case an AttributeError will be raised when trying to assign a value to that property, as demonstrated below:
class C:
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
c = C(3)
print(c.x)
try:
c.x = 4
except AttributeError:
print("An attribute error was raised")Output:
3
An attribute error was raised