Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top