Class methods are methods that are bound to the class rather than an instance of the class. They are defined using the `@classmethod` decorator and can be called on both the class itself and its instances. Class methods have access to the class itself and can modify class-level attributes or perform operations related to the class. Let's take an example of a `MathUtils` class to understand how class methods work:
class MathUtils: PI = 3.14159 @classmethod def circle_area(cls, radius): return cls.PI * radius**2 @classmethod def circle_circumference(cls, radius): return 2 * cls.PI * radius
In this code, we define a `MathUtils` class with two class methods: `circle_area` and `circle_circumference`. These methods perform calculations related to circles and use the class-level attribute `PI`. To use the class methods, we can call them directly on the class itself or on an instance of the class:
print(MathUtils.circle_area(5)) # Output: 78.53975 print(MathUtils.circle_circumference(5)) # Output: 31.4159 math_obj = MathUtils() print(math_obj.circle_area(3)) # Output: 28.27431 print(math_obj.circle_circumference(3)) # Output: 18.84954
78.53975 31.4159 28.27431 18.849539999999998
In this code, we call the `circle_area` and `circle_circumference` class methods both on the `MathUtils` class itself and on an instance of the class (`math_obj`). The class methods have access to the class-level attribute `PI` and perform calculations based on the provided radius. Class methods are useful when you need to perform operations that are related to the class as a whole, rather than specific instances. They can be used to modify class-level attributes, perform calculations, or implement class-specific functionality. It's important to note that class methods have access to the class itself through the `cls` parameter, which is automatically passed as the first argument. By convention, the first parameter of a class method is named `cls`, but you can use any valid parameter name.