Write instance methods that read and modify an object’s attributes.
How It Works
An instance method uses self to access the state of the object on which it was invoked. It is appropriate for operations that depend on or update that particular instance.
Keep business validation near operations that change the object.
Step-by-Step Example
class InventoryItem:
def __init__(self, stock_quantity):
self.stock_quantity = stock_quantity
def restock(self, additional_units):
self.stock_quantity += additional_units
item = InventoryItem(4)
item.restock(3)
print(item.stock_quantity)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
7
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Add a method for consuming stock and reject negative quantities.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Accidentally modifying a class-level variable instead of the instance state.
- Calling a method that updates state while assuming it returns the new count.
Key Takeaways
- Write instance methods that read and modify an object’s attributes.
- An instance method uses self to access the state of the object on which it was invoked.
- Keep business validation near operations that change the object.