Skip to main content

Accessor and Mutator methods - Python

·157 words·1 min
Vimal A R
Author
Vimal A R
Still figuring it out!

A method defined within a class can either be an Accessor or a Mutator method.

An Accessor method returns the information about the object, but do not change the state or the object.

A Mutator method, also called an Update method, can change the state of the object.

Consider the following example:

 1In [10]: a = [1,2,3,4,5]
 2
 3In [11]: a.count(1) Out[11]: 1
 4
 5In [12]: a.index(2) Out[12]: 1
 6
 7In [13]: a Out[13]: [1, 2, 3, 4, 5]
 8
 9In [14]: a.append(6)
10
11In [15]: a Out[15]: [1, 2, 3, 4, 5, 6]

The methods a.count() and a.index() are both Accessor methods since it doesn't alter the object a in any sense, but only pulls the relevant information.

But a.append() is a mutator method, since it effectively changes the object (list a) to a new one.

In short, knowing the behavior of a method is helpful to understand how it alters the objects it acts upon.

Related