Section 6.10 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
yc, and the perimeter point is in
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:
We called this function
area2to distinguish it from the
areafunction 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, yc, xp, yp): return area(distance(xc, yc, xp, yp))
You have attempted of activities on this page.