Methods of objects we’ve looked at so far are called by an instance of a class, which is then passed to the self parameter of the method.
Class methods are different – they are called by a class, which is passed to the cls parameter of the method.
A common use of these are factory methods, which instantiate an instance of a class, using different parameters than those usually passed to the class constructor.
Class methods are marked with a classmethod decorator.
def __init__(self, width, height):
self.width = width
self.height = height
return self.width * self.height
def new_square(cls, side_length):
return cls(side_length, side_length)
square = Rectangle.new_square(5)
new_square is a class method and is called on the class, rather than on an instance of the class. It returns a new object of the class cls.
Static methods are similar to class methods, except they don’t receive any additional arguments; they are identical to normal functions that belong to a class.
They are marked with the staticmethod decorator.
def __init__(self, toppings):
self.toppings = toppings
if topping == “pineapple”:
raise ValueError(“No pineapples!”)
ingredients = [“cheese”, “onions”, “spam”]
if all(Pizza.validate_topping(i) for i in ingredients):
pizza = Pizza(ingredients)
CLICK ON THE BUTTON BELOW TO GO TO THE PYTHON MAIN COURSE PAGE.
©️ License: All Rights Reserved
CONTACT HOLLA TECH – LEARN SUPPORT