Created
March 24, 2023 20:49
-
-
Save ozgurozkok/e6ca52c34ccf8d0344194612fb563584 to your computer and use it in GitHub Desktop.
getters, setters and properties in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person: | |
def init(self, name, age): | |
self.name = name | |
self._age = age # Use a private attribute to store the age | |
@property | |
def age(self): # This is a getter method for the age property | |
print("Getting age") | |
return self._age | |
@age.setter | |
def age(self, value): # This is a setter method for the age property | |
print("Setting age") | |
if isinstance(value, int) and value > 0: | |
self._age = value | |
else: | |
raise ValueError("Age must be a positive integer") | |
p = Person("Alice", 25) | |
print(p.age) # Getting age 25 | |
p.age = 30 # Setting age | |
print(p.age) # Getting age 30 | |
p.age = -10 # Setting age ValueError: Age must be a positive integer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment