๐Ÿ“ Change Methods in Python ๐Ÿš€#

In object-oriented programming, change methods (often called mutator methods or setters) are responsible for modifying the internal state of an object. They provide a controlled way to update attributes, ensuring that any rules or constraints are respected.

What Are Change Methods?#

  • Definition: A change method is a function within a class that modifies an objectโ€™s data (attributes).

  • Purpose: They offer a structured and controlled way to update an attribute so you donโ€™t accidentally violate constraints or introduce inconsistencies.

Example Use Cases#

  1. Validation: Ensure new values meet specific criteria (e.g., min/max range).

  1. Consistency: When one attribute changes, another might need to update automatically.

  1. Logging: Record changes or trigger events when certain attributes are modified.

Why Use Change Methods Instead of Direct Attribute Access?#

  1. Encapsulation

    • You can hide the internal details of how data is stored.

    • The class controls how external code can interact with those details.

  1. Validation & Error Handling

    • Check whether incoming data is valid (e.g., a temperature sensor reading must be above -273.15 ยฐC).

    • Raise errors or set defaults when invalid data is supplied.

  1. Maintainability

    • If you need to change the way data is stored or processed, you can modify the method without breaking external code.

Basic Structure of a Change Method#

Below is a simple example where we manage a machineโ€™s operational speed. Notice how we handle validation in the set_speed method rather than letting the user directly modify speed:

class Machine:
    def __init__(self, max_speed):
        self.__speed = 0
        self.__max_speed = max_speed

    def set_speed(self, new_speed):
        if 0 <= new_speed <= self.__max_speed:
            self.__speed = new_speed
            print(f"Machine speed set to {new_speed}")
        else:
            print(f"Error: speed must be between 0 and {self.__max_speed}")

    def get_speed(self):
        return self.__speed


# Usage
m = Machine(100)
m.set_speed(50)  # Machine speed set to 50
m.set_speed(150)  # Error: speed must be between 0 and 100
Machine speed set to 50
Error: speed must be between 0 and 100