0

I saw in another question that you can get and set class attributes like so:

class SomeClass:
    def __init__(self, name):
        self.name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, val):
        self._name = val
        

I'm just wondering why we do this when it looks like I can also just do:

x = SomeClass(name='Ari')
x.name = 'StackOverflow'

Can someone explain to me the purpose of the @property and @<attribute>.setter

Ari
  • 5,301
  • 8
  • 46
  • 120
  • 2
    You would typically have this in `__init__()`: `self._name = name` – Mark Jun 25 '20 at 02:23
  • Please refer the [documentation](https://docs.python.org/3/library/functions.html#property). – ywbaek Jun 25 '20 at 02:24
  • Those `property`s are *totally pointless*. Don't do it that way. The whole *point* of property is to *avoid* boilerplate getters and setters. – juanpa.arrivillaga Jun 25 '20 at 02:30
  • @MarkMeyer well, in this case, you would just do `self.name = name` – juanpa.arrivillaga Jun 25 '20 at 02:30
  • @juanpa.arrivillaga I am assuming (maybe incorrectly) that this example was simplified to make a minimal, complete example. Clearly, if you are doing nothing in getter or setter other than getting and setting there's no point. On the other hand, this is almost *exactly* the example in the documentation, which presumably is not there to be *totally pointless*. – Mark Jun 25 '20 at 02:42

0 Answers0