1、使用lambda表达式代替局部函数
def get_math_func(type): result = 1 # 该函数返回的是lambda表达式 if type == 'square': return lambda n: n * n elif type == 'cube': return lambda n: n * n * n else: return lambda n: (1+n) * n / 2 # 调用 get_math_func(),程序返回一个嵌套函数 math_func = get_math_func(type='square') print(math_func(3)) math_func = get_math_func(type='cube') print(math_func(3)) math_func = get_math_func(type='other') print(math_func(3))