Contrast instructions that transform data with objects that combine data and behavior.
How It Works
A procedural design usually passes data into functions, while object-oriented design groups state with methods that operate on it. Both can solve the same problem. Start with a function for a simple calculation and consider a class when several operations share and protect state.
Use objects for responsibilities and invariants, not simply because OOP is available.
Step-by-Step Example
def total_price(quantity, unit_price):
return quantity * unit_price
class ShoppingCart:
def __init__(self):
self.items = []
def add(self, price):
self.items.append(price)
def total(self):
return sum(self.items)
cart = ShoppingCart()
cart.add(total_price(2, 4))
print(cart.total())
Understanding the Example
- The function definition gives the operation a reusable name and makes its inputs explicit.
- The class groups related state and methods so each instance can manage its own values.
A successful run of this example prints the following output:
8
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 remove() method to the cart and consider what should happen with a missing item.
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
- Creating a class for every tiny utility even when a plain function is clearer.
- Placing every variable in global scope instead of giving a class or function clear ownership.
Key Takeaways
- Contrast instructions that transform data with objects that combine data and behavior.
- A procedural design usually passes data into functions, while object-oriented design groups state with methods that operate on it.
- Use objects for responsibilities and invariants, not simply because OOP is available.