+ 1

What is property decorator how does it work and what does it even do ? Setter ? Getter?

Евгений can you please explain what is property? Setter ? Getter ? For now all i know is that when i use @property i don't have to call the function with the () at the end of it's name + it's no longer editable so basically i can't seem to see any use for it for example in this code i can remove the property decorator and the code won't be effected at all (only used it as it was about the property lesson in this course) class Player: def __init__(self, name, lives): self.name = name self._lives = lives def hit(self): self._lives -= 1 @property def isAlive(self): if self._lives > 0: return True else: return False p = Player("Cyberpunk77", int(input())) i = 1 while True: p.hit() print("Hit # " + str(i)) i += 1 if not p.isAlive: print("Game Over") break

29th Aug 2023, 11:05 AM
Intermediate Depression
Intermediate Depression - avatar
1 Réponse
+ 2
getters and setters are used if you don't want direct access to some class attributes. The @property decorator is used for getter of 'private' attributes. The @attribute.setter decorator is used for setters. Because the values have to pass through a method, you can customize and add conditions to what values are acceptable and how values are presented to the user. You don't really have to use them, but they provide a nicer interface if you do. https://code.sololearn.com/cJxDVg6eKCez/?ref=app
29th Aug 2023, 1:33 PM
Bob_Li
Bob_Li - avatar