I am learning getters and setters , what I understand is that they are used so that no one could change the object's attributes directly. In the example
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
def get_age(self):
return self._age
def set_age(self, new_age):
if isinstance(new_age, int) & new_age>0 & new_age<120:
self._age = new_age
def get_name(self):
return self._name
def __str__(self):
return 'Person[' + self._name + '] is ' + str(self._age)
p1 = Person("Sandeep", 49)
I created an object p1
where I set the age 49. As I have made a set_age
function so I expect we can change the age of p1
through set_age
only, not through the routine way. But it is not happening, I am able to change the age of p1
through , for example, p1._age = 35
as well. Then, what is the advantage to make set_age
function, if I am still able to access the attributes directly?
I think, I am missing something, please help.