Skip to content

Instantly share code, notes, and snippets.

@jakelevi1996
Created May 29, 2020 22:49
Show Gist options
  • Select an option

  • Save jakelevi1996/128befd3c509d3ad5cf30b6b458bf08c to your computer and use it in GitHub Desktop.

Select an option

Save jakelevi1996/128befd3c509d3ad5cf30b6b458bf08c to your computer and use it in GitHub Desktop.
Read-only attributes in Python

Read-only attributes in Python

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment