문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top