Accessor and Mutator in Python

Since it's a good idea to keep internal data of an object private , we often need methods in the class interface to allow the user of objects to modify or access the internally stored data, in a controlled way. A method defined within a class can either be an Accessor or a Mutator method. An accessor method is a function that returns a copy of an internal variable or computed value. A common practice is to name these with the word get. A mutator method is a function that modifies the value of an internal data variable in some way. The simplest form of mutator function is one that sets a variable directly to a new value. A common practice is to name these with the word set. example
class MyClass(): def __init__(self): self.__my_attr = 3 def set_my_attr(self,val): self.__my_attr = val def get_my_attr(self): return self.__my_attr obj1 = MyClass() print (obj1.get_my_attr()) obj1.set_my_attr(7) print (obj1.get_my_attr())

In the example above,

The methods obj1.get_my_attr() is Accessor methods since it doesn’t alter the object a in any sense, but only pulls the relevant information. But obj1.set_my_attr(7) is a mutator method, since it effectively changes the object to a new one.