Search code examples
python-3.xenumsgetter-setter

How can I add a getter and a setter to an enum variable?


I have a small ( simplified for the purpose of this question ) class such as :

class ShortStatus1:
    class Shutter(Enum):
        CLOSED = '0', ErrorType.NONE
        OPEN = '1', ErrorType.NONE

    def __init__(self):
        self.shutter = ShortStatus1.Shutter.OPEN

I would like to add a getter and a setter to the variable itself if it is possible such as :

sh = ToTLMShort()
sh.shutter.set(ShortStatus1.Shutter.CLOSED)
print(sh.shutter.get())

would print Shutter.CLOSED

The issue I have is that I do not understand how I can enclose self.shutter in a getter and a setter that way ( I would like to avoid a sh.set_shutter(ShortStatus1.Shutter.CLOSED) signature if possible ).
The setter is important as it gives me the possibility to ensure that the given variable is of the right type and avoid user mistakes ( the code is going to be used by a lot of people with very varying levels of expertise )

Is there a simple way to do so or do I need to add an extra class for the sole purpose of encapsulating the variable ?


Solution

  • You can use the @property decorator and _ in front of the shutter class attribute:

    def __init__(self):
        self._shutter = ShortStatus1.Shutter.OPEN
    
    @property
    def shutter(self):
        return self._shutter
    
    @shutter.setter
    def shutter(self, value):
        self._shutter = value
    

    Then, if you do:

    if __name__ == '__main__':
        a = ShortStatus1()
        print(a.shutter)
        a.shutter = ShortStatus1.Shutter.CLOSED
        print(a.shutter)
    

    Output:

    Shutter.OPEN
    Shutter.CLOSED