Use @classmethod for methods working with classes and alternate constructors.
How It Works
@classmethod binds the receiving class as cls, so it can construct instances that respect subclassing. It is useful for named constructors and class-wide operations.
A staticmethod does not receive cls, so it serves a different purpose.
Step-by-Step Example
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
@classmethod
def from_fahrenheit(cls, fahrenheit):
return cls((fahrenheit - 32) * 5 / 9)
measurement = Temperature.from_fahrenheit(68)
print(round(measurement.celsius, 1))
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:
20.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
Create a from_minutes alternate constructor for a Duration class.
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
- Using a classmethod when per-instance data is necessary but unavailable.
- Hardcoding the base class in an alternate constructor instead of using cls.
Key Takeaways
- Use @classmethod for methods working with classes and alternate constructors.
- @classmethod binds the receiving class as cls, so it can construct instances that respect subclassing.
- A staticmethod does not receive cls, so it serves a different purpose.