Place small stateless helpers inside classes using @staticmethod.
How It Works
@staticmethod prevents automatic binding of an instance or class argument. It is helpful for a closely related utility, though a normal module-level function is often just as appropriate.
A classmethod can access cls; a staticmethod cannot automatically access class state.
Step-by-Step Example
class PriceTools:
@staticmethod
def add_tax(base_price, tax_rate):
return base_price * (1 + tax_rate)
print(PriceTools.add_tax(100, 0.18))
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:
118.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
Add a static validation helper for checking a nonnegative price.
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
- Defining a staticmethod with self and expecting the instance to be passed automatically.
- Placing unrelated functions in a class just to create a namespace.
Key Takeaways
- Place small stateless helpers inside classes using @staticmethod.
- @staticmethod prevents automatic binding of an instance or class argument.
- A classmethod can access cls; a staticmethod cannot automatically access class state.