Fix the Factory Method
Intermediate · Fix the bug · from Python @classmethod vs @staticmethod: When to Use Each
From the lesson: Python @classmethod vs @staticmethod: When to Use Each
Imagine a company with three kinds of employees. Regular employees work on their own tasks (they need to know about themselves). Managers can hire new employees for the whole department (they need to know about the department).
Read the lessonThis Rectangle class has a factory method with two bugs. Fix them so the code prints:
5 x 5class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def from_square(cls, side):
return cls(side, side)
def __str__(self):
return f'{self.width} x {self.height}'
square = Rectangle.from_square(5)
print(square)
More Classmethod and Staticmethod exercises
- Create a Factory MethodBeginner
- Add a Static ValidatorBeginner
- Predict the Method OutputIntermediate
- Build a Temperature ConverterAdvanced
All Python exercises · 50 practice problems · Object-Oriented Programming quiz