Question

For example:

class Example:
    def __init__(self, value):
        self.value = value

I want to make it so people can't change what self.value is after it's been initialized. So it would raise an exception if someone tried:

>>> c = Example(1)
>>> c.value = 2

I would like for it to raise an error or simply make it not possible.

Was it helpful?

Solution

You can use a property:

class Example(object):
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

Note that the value with still be writable as example_object._value, but prepending an underscore to an attribute name is a convention for telling other developpers this attribute is not part of the class public API and should not be used.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top