๐ 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#
Validation: Ensure new values meet specific criteria (e.g., min/max range).
Consistency: When one attribute changes, another might need to update automatically.
Logging: Record changes or trigger events when certain attributes are modified.
Why Use Change Methods Instead of Direct Attribute Access?#
Encapsulation
You can hide the internal details of how data is stored.
The class controls how external code can interact with those details.
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.
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