Accessor and Mutator in Python

In object-oriented programming, accessor and mutator methods are used to control how attributes (data members) of a class are accessed and modified. These methods help maintain encapsulation and data integrity by providing controlled access to the internal state of an object. In Python, accessor methods are typically referred to as "getter" methods, and mutator methods are referred to as "setter" methods.

Accessor (Getter) Methods in Python

Accessor methods are used to retrieve the values of attributes without directly accessing them. They provide controlled access to the object's internal state and can be used to perform any necessary calculations or manipulations before returning the value.

class Circle: def __init__(self, radius): self._radius = radius def get_radius(self): return self._radius circle = Circle(5) radius = circle.get_radius() print(radius) # Output: 5

In this example, the get_radius() method is an accessor method that allows controlled access to the _radius attribute of the Circle class.

Mutator (Setter) Methods in Python

Mutator methods are used to modify the values of attributes while enforcing certain conditions or validations. They ensure that changes to the object's state are done in a controlled manner.

class Rectangle: def __init__(self, width, height): self._width = width self._height = height def set_width(self, width): if width > 0: self._width = width else: print("Width must be positive.") rectangle = Rectangle(10, 5) rectangle.set_width(15) print(rectangle._width) # Output: 15 rectangle.set_width(-5) # Output: Width must be positive.

Here, the set_width() method is a mutator method that changes the _width attribute only if the provided width is positive.


Using accessor and mutator methods, you can provide a clear interface for working with an object's attributes, ensuring that changes to its internal state adhere to the defined rules and constraints. This approach enhances encapsulation, making the code more maintainable and robust. Additionally, it allows you to make modifications to the implementation of the class without affecting the code that uses it, as long as the interface provided by the accessor and mutator methods remains consistent.