函数嵌套

函数嵌套

一、函数的嵌套定义

函数内部定义的函数,无法在函数外部使用内部定义的函数。

def f1():
    def f2():
        print('from f2')
    f2()


f2()  # NameError: name 'f2' is not defined
def f1():
    def f2():
        print('from f2')
    f2()


f1()
from f2

现在有一个需求,通过给一个函数传参即可求得某个圆的面积或者圆的周长。也就是说把一堆工具丢进工具箱内,之后想要获得某个工具,直接从工具箱中获取就行了。

from math import pi


def circle(radius, action='area'):
    def area():
        return pi * (radius**2)

    def perimeter():
        return 2*pi*radius
    if action == 'area':
        return area()
    else:
        return perimeter()


print(f"circle(10): {circle(10)}")
print(f"circle(10,action='perimeter'): {circle(10,action='perimeter')}")
circle(10): 314.1592653589793
circle(10,action='perimeter'): 62.83185307179586

二、函数的嵌套调用

def max2(x, y):
    if x > y:
        return x
    else:
        return y


def max4(a, b, c, d):
    res1 = max2(a, b)
    res2 = max2(res1, c)
    res3 = max2(res2, d)
    return res3


print(max4(1, 2, 3, 4))
4
posted @ 2019-11-16 13:57  つつつつつつ  阅读(252)  评论(0编辑  收藏  举报