Getters and Setters are simply methods that aid in encapsulation. They are not specific to Python but rather Object-Oriented Programming in general;
They are alternatively called mutator/accessor methods.
What's their point?
They hide implementation details
Users of your class don't need to know the property name you are using internally to keep track of the name
of your User
. You just tell them to call .getName()
to get the name and that's it.
They allow you to add validation checks
Had the property been exposed for you to arbitrarily change, without using a set
method, you could have made erroneous changes, e.g setting the name of your User
instance to '12'.
You can perform other work before you actually mutate a property
Sometimes you may want to keep a history of the mutations that took place on
your instance. Using a setter allows you to trigger other functions before actually changing the property value, for example calling a logNameChanges
method.
These are the most important reasons I've ever practically came across. There's a more exhaustive list here.