1

Is it better to use method for some type of following usage(update or get a variable) or property form is preferable?

class Player(object):
    def __init__(self, name):
        self.name = name
        self.score = 0


    def update_score(self, x):
        self.score += x


    def get_score(self):
        return self.score


    def get_name(self):
        return self.name

for example:

using property form:

self.score

instead of method form:

def get_score(self):
    return self.score

Do you use the method form just to better understand what it is going to do?

Mostafa Najmi
  • 315
  • 1
  • 4
  • 11
  • 10
    You don't need getters and setters in a case like this. – buran Jan 30 '22 at 21:34
  • Generally, the `@property` decorator (and associated decorators) are used to prevent arbitrary (or even intentional) overwriting of the attribute’s value; as the property will be deemed ‘read-only’; therefore the need for a setter. In this scenario, there are no `@properry` decorators in use, so no need for a getter/setter. – S3DEV Jan 30 '22 at 21:38
  • I do agree. But I saw lots of different repo from famous programmer which was like this form. - @buran – Mostafa Najmi Jan 30 '22 at 21:39
  • OOP generally or python specifically? – tdelaney Jan 30 '22 at 21:41
  • Are you talking about actual `property()`? – JonSG Jan 30 '22 at 21:43
  • Thank you @S3DEV. could you please tell me an example which needs to use getter/setter? – Mostafa Najmi Jan 30 '22 at 21:44
  • @tdelaney python specifically. – Mostafa Najmi Jan 30 '22 at 21:47
  • 4
    Use the attribute directly until you have a good reason to hide it behind a property; then you can replace it with a property without the users of your class needing to make any syntactic changes. (They may need to adjust to the changing *semantics* of the property, but that's another issue.) – chepner Jan 30 '22 at 21:59
  • 1
    @MostafaNajmi Getters and setters are useful for controlling access to a value (e.g. a private setter), or for adding additional logic (e.g. validation) before a value is set. A getter may be used to handle null cases (e.g. return 0 instead of null if the backing variable is null). – John Glenn Jan 30 '22 at 22:00
  • 1
    And, you can do both: `@property def score(self): return self._score` to provide read-only access to the score, and `def update_score(self, x): self._score += x` to allow increasing the score without providing (well, condoning) arbitrary write access to the score. – chepner Jan 30 '22 at 22:02

0 Answers0