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

5
  • 2
    You would typically have this in __init__(): self._name = name Commented Jun 25, 2020 at 2:23
  • Please refer the documentation. Commented Jun 25, 2020 at 2:24
  • Those propertys are totally pointless. Don't do it that way. The whole point of property is to avoid boilerplate getters and setters. Commented Jun 25, 2020 at 2:30
  • @MarkMeyer well, in this case, you would just do self.name = name Commented Jun 25, 2020 at 2: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. Commented Jun 25, 2020 at 2:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.