Why - or why not - is it good practice to use getters and setters specifically in Python OOP?
My textbook states the following:
import random
class Die(object):
"""Simulate a generic die."""
def __init__(self):
self.sides = 6
self.roll()
def roll(self):
"""Updates the die with a random roll."""
self.value = 1+random.randrange(self.sides)
return self.value
def getValue(self):
"""Return the last value set by roll()."""
return self.value
def main():
d1,d2 = Die(),Die()
for n in range(12):
print d1.roll(),d2.roll()
main()
The getValue() method, called a getter or an accessor, returns the value of the value instance variable. Why write this kind of function? Why not simply use the instance variable? We’ll address this in the FAQ’s at the end of this chapter.
However, there is no FAQ at the end of the chapter, and so it is never explained as to why getters are used in Python OOP.
I've tried reading other places, but I have not found a good explanation anywhere. Most answers on SO are about Java, and I've read that it is not relevant to Python...
Can someone please help me understand why it is good practice to use them? Or if not, why not?