Problem overview
You write an abstract class Shape and the areas of three shapes. Shape has two abstract methods, area() and name(), and one concrete method, describe(), which returns text such as Square with area 25: the name, then with area, then the area.
Three classes inherit from it. Their constructors and name() methods are given; you write each area():
Rectangle(width, height): width times height;Square(side): side times side;RightTriangle(a, b): the two sides meeting at the right angle, areaa * b / 2rounded down.
For Rectangle(3, 4), Square(5) and RightTriangle(3, 4) the tests print Rectangle with area 12, Square with area 25 and Right triangle with area 6.
Approach
An abstract class is a template: it says what every shape must be able to do (area and name) without saying how. It can also hold code that is the same for all shapes. describe() is that code. It calls self.name() and self.area() without knowing which shape it runs on, and each shape's own methods fill in the text. So describe is written once and works for every shape, including ones added later.
In Python, you make a class abstract by inheriting from ABC (from the abc module) and marking each abstract method with @abstractmethod. The body is just pass.
Step by step
- Abstract
area: put@abstractmethodabovedef area(self)inShape, with the bodypass. - Abstract
namethe same way. - Write
describe: returnself.name(), then" with area ", thenstr(self.area()). The area is a number, andstrturns it into text so that+can join it. - Rectangle's area:
self._width * self._height. - Square's area:
self._side * self._side. - Triangle's area:
self._a * self._b // 2. A right triangle is half of an a by b rectangle, and//drops the fraction.
The solution in Python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): pass
@abstractmethod
def name(self): pass
def describe(self):
return self.name() + " with area " + str(self.area())
class Rectangle(Shape):
def __init__(self, width, height):
self._width = width
self._height = height
def name(self):
return "Rectangle"
def area(self):
return self._width * self._height
class Square(Shape):
def __init__(self, side):
self._side = side
def name(self):
return "Square"
def area(self):
return self._side * self._side
class RightTriangle(Shape):
def __init__(self, a, b):
self._a = a
self._b = b
def name(self):
return "Right triangle"
def area(self):
return self._a * self._b // 2
Running the three examples:
for shape in [Rectangle(3, 4), Square(5), RightTriangle(3, 4),
RightTriangle(3, 5), Rectangle(1, 7), RightTriangle(1, 1)]:
print(shape.describe())
Rectangle with area 12
Square with area 25
Right triangle with area 6
Right triangle with area 7
Rectangle with area 7
Right triangle with area 0
Adding a shape later
The benefit of the abstract class shows when a new shape appears. In a file of your own, a parallelogram needs only a constructor, a name and an area. It inherits describe unchanged:
class Parallelogram(Shape):
def __init__(self, base, height):
self._base = base
self._height = height
def name(self):
return "Parallelogram"
def area(self):
return self._base * self._height
shapes = [Square(2), Parallelogram(6, 4)]
for shape in shapes:
print(shape.describe())
print(sum(s.area() for s in shapes))
Square with area 4
Parallelogram with area 24
28
Nothing in Shape changed. Any code that holds a list of shapes, like the loop above, handles the new class as soon as it exists, because it only calls area() and describe(). This is the same idea as a loop that calls one method on mixed objects: the caller depends on the promise in Shape, not on the individual classes.
Python details
- Floor division.
3 * 5 / 2is7.5, but3 * 5 // 2is7, and1 * 1 // 2is0. With/,describe()would printRight triangle with area 7.5. Since the sides are positive, flooring and "rounding down" agree. - The class can't be created.
Shape()raisesTypeError: Can't instantiate abstract class Shape without an implementation for abstract methods 'area', 'name'. - A child must fill in every abstract method. A
Circle(Shape)that defines onlynamecan't be created either: the error namesareaas missing. That is why each shape in the starter code already has aname. - Precedence.
self._a * self._b // 2multiplies first, then divides, because*and//have the same precedence and group from the left. - The abstract body.
def area(self): passon one line is valid; the body never runs, since the children replace it.
How one call to describe runs
Take RightTriangle(3, 5).describe(). Python finds describe in Shape, because the triangle class doesn't define its own. Inside it, self is the triangle, so self.name() runs the triangle's name and gives "Right triangle". Then self.area() runs the triangle's area: 3 times 5 is 15, and 15 // 2 is 7. The text is "Right triangle", " with area " and "7" joined together. For a square the same line of code produces a different text, because self is a different object.
This is why the abstract methods exist. describe calls self.area(), so every shape must have one, and Python checks that when you create the object rather than when the call finally fails in the middle of a program.
Edge cases and common mistakes
- Using
/instead of//gives a float, and for odd products the text shows.5. - Forgetting
str()indescriberaises aTypeError, because Python won't join text and a number with+. - Forgetting
ABCas the parent. Then@abstractmethodis accepted but not enforced, and nothing stops you from creating a plain shape. - Writing
describein each shape. It works, but the point is to write it once inShape. - Forgetting the calls' parentheses in
describe:self.namewithout()is a method object, not the text. - A triangle of 1 by 1 has area 0 here, not 1, which is what the third example shows.
Testing
These inputs are worth trying, with the text describe() returns for each:
Rectangle(1, 1)givesRectangle with area 1.RightTriangle(9999, 1)givesRight triangle with area 4999: 9999 is odd, so half of it rounds down.RightTriangle(10000, 10000)givesRight triangle with area 50000000.Square(10000)givesSquare with area 100000000. Python integers don't overflow, so the largest sizes need no special care.
The area is always a whole number: only the triangle divides, and // keeps its result an integer.
One more difference from an interface: Shape is not only a promise, because it also carries working code, describe. That mix of promised methods and shared code is what an abstract class is for. When a class has only promises, it is usually called an interface.
