Jan-11-2019, 07:13 PM
If you're not doing any extra work with the setter/getter, then making the methods is... a waste of your time? If you want it publicly available, let it be publicly available.
If you DO have extra work to do (such as using validation to make sure the value it's being set to makes sense), then the @property decorator is pretty awesome: https://docs.python.org/3/library/functi...l#property
If you DO have extra work to do (such as using validation to make sure the value it's being set to makes sense), then the @property decorator is pretty awesome: https://docs.python.org/3/library/functi...l#property
>>> class spam: ... def __init__(self, val): ... self.foo = val ... @property ... def foo(self): ... return self.__foo ... @foo.setter ... def foo(self, val): ... if not isinstance(val, int): ... raise Exception("Slow down there, cowboy.") ... self.__foo = val ... >>> x = spam(5) >>> x.foo 5 >>> x.foo = 7 >>> x.foo 7 >>> x.foo = "bar" Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 10, in foo Exception: Slow down there, cowboy.