6.9. Composition¶
As we have already seen, you can call one function from within another. This ability to build functions by using other functions is called composition.
As an example, we’ll write a function that takes two points, the center of the circle and a point on the perimeter, and computes the area of the circle.
Assume that the center point is stored in the variables xc
and
yc
, and the perimeter point is in xp
and yp
. The first
step is to find the radius of the circle, which is the distance
between the two points. Fortunately, we’ve just written a function,
distance
, that does just that, so now all we have to do is use it:
radius = distance(xc, yc, xp, yp)
The second step is to find the area of a circle with that radius and return it. Again we will use one of our earlier functions:
result = area(radius)
return result
Wrapping that up in a function, we get:
def distance(x1: float, y1: float, x2: float, y2: float) -> float:
dx: float
dy: float
dsquared: float
result: float
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2.0 + dy**2.0
result = dsquared**0.5
return result
def area(radius: float) -> float:
b: float
b = 3.14159 * radius**2.0
return b
def area2(xc: float, yc: float, xp: float, yp: float) -> float:
radius: float
result: float
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
def main() -> None:
print(str(area2(0.0, 0.0, 1.0, 1.0)))
return None
main()
(ch06_newarea)
We called this function area2
to distinguish it from the area
function defined earlier. There can only be one function with a given
name within a module.
Note that we could have written the composition without storing the intermediate results.
def area2(xc: float, yc: float, xp: float, yp: float) -> float:
return area(distance(xc, yc, xp, yp))