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.
- The first step is to find the radius of the circle, which is the distance between the two points.
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
area2
to distinguish it from thearea
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, yc, xp, yp):
return area(distance(xc, yc, xp, yp))