i am new to python and i'm trying to understand the use of the 'getter'. it's use case is not obvious to me. if i use a property decorator on a method and im able to return a certain value, what exactly would i use 'getter' for.
class Person:
def __init__(self,name, age):
self._name = name
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self,new_age):
if isinstance(new_age,int) and 18 < new_age < 120:
self._age = new_age
The @property decorator adds a default getter on a given field in a Python class that triggers a function call upon accessing a property.
The @property decorator turns the age() method into a “getter” for a read-only attribute with the same name. If want a “setter” then add @age.setter
as you did in your question.
p = Person("John", 22)
print(p.age)
Output:
22