0

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 ?

  • 2
    Possible duplicate of [What's the pythonic way to use getters and setters?](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) – MisterMiyagi Jul 25 '19 at 09:56
  • Can you explain your problem/confusion? The idiomatic way to have getter/setter is to apply ``property`` in the class definition - ``ShortStatus1`` in your case. There is no need to add an additional class, and it has no bearing on the attribute type being an enum. – MisterMiyagi Jul 25 '19 at 09:59

1 Answers1

2

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
Dorian Turba
  • 3,260
  • 3
  • 23
  • 67