So far you have seen that the methods of the objects are called by the name of the instance of the class (object), which is passed as a self parameter within the method.
Class methods are different. These methods are called directly from the class that is passed as the cls parameter within the method. Class methods are marked with an @classmethod decorator. Generally these methods are used to instantiate a new class instance, passing the parameters different from those required by the manufacturer.
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def calculate_area(self): return self.width * self.height @classmethod def new_square(cls, side_length): return cls(side_length, side_length) square = Rectangle.new_square(5) print(square.calculate_area())
If you run the program you get:
As you can see, the class method is used to create a new instance using only one parameter (side) instead of the two required by the constructor (length, height)
Static methods are very similar to class methods. You can recognize them by having an @staticmethod decorator before the definition.
class Pizza: def __init__(self, toppings): self.toppings = toppings @staticmethod def validate_topping(topping): if topping == "pineapple": raise ValueError("No pineapple") else: return Trueingredients = ["cheese","onions","tomato"] if all(Pizza.validate_topping(i) for i in ingredients): Pizza = Pizza(ingredients)
From the example above, you can see a possible use, as a validation method with a control over the arguments before instantiating a new class object.