One loop, many kinds
After this: Loop over a list of mixed shapes, call one method on each, and read which version ran in the trace.
On this page · 8 sections · 3 checks
A drawing holds a mix of shapes: some circles, some rectangles. You want the total area. One way is a loop with a check inside: if this one is a circle, do the circle sum; if it is a rectangle, do the rectangle sum. Add a third kind of shape and the check grows again. The last two lessons give a better way.
One name, many kinds
Put all the shapes in one list and call area() on each. Every shape has an area, because every shape class is built on Shape, and each kind gives its own. The loop asks one question and never checks the kind. This is called : one name, many kinds.
By hand
The list holds Circle(1) and Rect(2, 3), and total starts at 0.0.
- First time round,
sis the circle.s.area()runs Circle'sarea: 3.141592653589793.totalbecomes 3.141592653589793. - Second time round,
sis the rectangle. The same lines.area()now runs Rect'sarea: 6.totalbecomes 9.141592653589793. - The loop ends. Rounded to two decimals, the total is 9.14.
The rule: the loop line is written once. Which area runs is decided afresh on each turn, by the object in s.
Watch it happen
This is the trace to spend time on. Step into the loop and watch two boxes. s changes on each turn. Then, when s.area() is called, a frame named area opens, and its selfthis box is Circle(r=1) the first time and Rect(w=2, h=3) the second. The marked line inside the frame differs too: line 1217 for the circle and line 2032 for the rectangle.
- Run the programRun it and step into the loop. On each turn, watch the box s change, then watch the frame named area open with a different object in its first box, and a different line marked inside it.
import math
class Shape: def area(self): return 0.0
class Circle(Shape): def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Rect(Shape): def __init__(self, w, h): self.w = w self.h = h
def area(self): return self.w * self.h
shapes = [Circle(1), Rect(2, 3)]total = 0.0for s in shapes: total = total + s.area()print(round(total, 2))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
The code
import math
class Shape: def area(self): return 0.0
class Circle(Shape): def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Rect(Shape): def __init__(self, w, h): self.w = w self.h = h
def area(self): return self.w * self.h
shapes = [Circle(1), Rect(2, 3)]total = 0.0for s in shapes: total = total + s.area()print(round(total, 2))9.14
import java.util.ArrayList;import java.util.List;
abstract class Shape { abstract double area();}
class Circle extends Shape { int r;
Circle(int r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }}
class Rect extends Shape { int w; int h;
Rect(int w, int h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }}
public class Main { public static void main(String[] args) { ArrayList<Shape> shapes = new ArrayList<>(List.of(new Circle(1), new Rect(2, 3))); double total = 0.0; for (Shape s : shapes) { total = total + s.area(); } System.out.println(String.format("%.2f", total)); }}9.14
Asking what kind it is
The loop never needed to know what kind each shape was. When you do need to ask, isinstance(c, Shape)c instanceof Shape answers whether the object in c is a Shape, counting anything built on Shape. A circle is a shape, so that is Truetrue. A circle is not a rectangle, so isinstance(c, Rect)c instanceof Rect is Falsefalse.
class Shape: def describe(self): return "a shape"
class Circle(Shape): def __init__(self, r): self.r = r
class Rect(Shape): def __init__(self, w, h): self.w = w self.h = h
c = Circle(1)print(isinstance(c, Shape))print(isinstance(c, Rect))print(c.describe())run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Use this sparingly. A loop full of such checks is the thing this lesson replaced.
Run it
Add Rect(1, 1) to the list and run it again; the total should grow by 1.
Check yourself
The list holds Circle(1) and then Rect(2, 3), and the loop body is total = total + s.area()total = total + s.area();. Which area runs on each turn?
The same classes, a different list. What does this print?
import math
class Shape: def area(self): return 0.0
class Circle(Shape): def __init__(self, r): self.r = r
def area(self): return math.pi * self.r * self.r
class Rect(Shape): def __init__(self, w, h): self.w = w self.h = h
def area(self): return self.w * self.h
total = 0.0for s in [Rect(1, 2), Circle(1)]: total = total + s.area()print(round(total, 2))import java.util.List;
abstract class Shape { abstract double area();}
class Circle extends Shape { int r;
Circle(int r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }}
class Rect extends Shape { int w; int h;
Rect(int w, int h) { this.w = w; this.h = h; }
@Override double area() { return w * h; }}
public class Main { public static void main(String[] args) { double total = 0.0; for (Shape s : List.of(new Rect(1, 2), new Circle(1))) { total = total + s.area(); } System.out.println(String.format("%.2f", total)); }}In the trace of the total, the second time area is running, what does the selfthis box inside its frame hold?
Honesty notes
- Put objects of several classes in one list and call one method on each, without checking what kind each is.
- Say which version of the method runs on each turn of the loop: the one belonging to the object in the loop box.
- Work out the total area of a circle of radius 1 and a 2 by 3 rectangle: 9.14 to two decimals.
- Say what abstract means in Java (a promise with no code, and no plain Shape objects), and that Python has no such word.
- Ask whether an object is a kind of something with isinstance in Python or instanceof in Java.