Choose between a function and a class based on state and responsibility.
How It Works
If a calculation depends only on its arguments and returns a result, a function is usually enough. A class is useful when the same object carries changing state and several operations maintain its invariants. Avoid inventing object state solely to wrap a one-line helper.
Favor the design that makes correct usage obvious; procedural and object-oriented approaches can coexist.
Step-by-Step Example
def discount_price(amount, percent):
return amount * (1 - percent / 100)
class TemperatureSensor:
def __init__(self):
self.readings = []
def record(self, value):
self.readings.append(float(value))
def average(self):
return sum(self.readings) / len(self.readings) if self.readings else None
sensor = TemperatureSensor()
sensor.record(20)
sensor.record(22)
print(discount_price(100, 10), sensor.average())
Understanding the Example
- The function definition gives the operation a reusable name and makes its inputs explicit.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
90.0 21.0
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
Write the sensor as plain functions and discuss which design is easier to extend.
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
- Converting a simple stateless operation into a class with needless instance attributes.
- Allowing a stateful object to reach an inconsistent state because methods skip validation.
Key Takeaways
- Choose between a function and a class based on state and responsibility.
- If a calculation depends only on its arguments and returns a result, a function is usually enough.
- Favor the design that makes correct usage obvious; procedural and object-oriented approaches can coexist.