首页 > 技术文章 > 日常学习记录-01

zack-dong 2020-05-06 19:51 原文

1、局部函数的使用,可以用于测试自动化编写公共方法,根据传入的type,执行不同的函数体

# 定义一个函数,包含局部函数


def get_mach_func(type, nn):
    # 定义局部函数1:计算平方
    def square(n):
        return n * n

    # 定义局部函数2:计算立方
    def cube(n):
        return n * n * n

    # 定义局部函数3:计算阶乘
    def factorial(n):
        num = 1
        for index in range(2, n+1):
            num *= index
        return num

    # 调用局部函数
    if type == 'square':
        return square(n=nn)
    elif type == 'cube':
        return cube(n=nn)
    else:
        return factorial(n=nn)


# 使用函数
print(get_mach_func(type='square', nn=3))
print(get_mach_func(type='cube', nn=3))
print(get_mach_func(type='', nn=3))

2、使用函数变量,来调用函数,方便、高效----就是将函数赋值给变量

# 定义一个计算乘方的函数
def pow(base, exponent):
    result = 1
    for i in range(1, exponent + 1):
        result *= base
    return result


# 将 pow 函数赋值给my_fun, 则my_fun 可被当成pow使用
my_fun = pow
print(my_fun(3, 4))


# 定义一个计算面积的函数
def area(width, height):
    return width * height


# 将 area函数赋值给my_fun, 则my_fun 可被当成area使用
my_fun = area
print(my_fun(3, 4))

3、使用函数作为函数形参--- 就是将函数作为一个动态参数传给另外一个函数

# 定义函数类型的形参,其中fn是一个函数
def map(data, fn):
    result = []
    # 遍历data列表中的每一个元素,并用fn函数对每个元素进行计算
    # 然后将计算结果作为新数组的元素
    for e in data:
        result.append(fn(e))
    return result


# 定义一个计算平方的函数
def square(n):
    return n * n


# 定义一个计算立方的函数
def cube(n):
    return n * n * n


# 定义一个阶乘的函数
def factorial(n):
    result = 1
    for index in range(2, n+1):
        result *= index
    return result


data = [3, 4, 6, 7, 10]
print('原始数据为:', data)
# 下面程序代码调用map()函数三次,每次调用时传入不同的函数
print('计算数组元素的平方')
print(map(data, square))
print('计算数组元素的立方')
print(map(data, cube))
print('计算数组元素的阶乘')
print(map(data, factorial))

4、使用函数作为返回值

def get_math_func(type):

    # 定义局部函数1:计算平方
    def square(n):
        return n * n
    # 定义局部函数2:计算立方

    def cube(n):
        return n * n * n

    # 定义局部函数3:计算阶乘
    def factorial(n):
        result = 1
        for index in range(2, n+1):
            result *= index
        return result

    # 返回局部函数
    if type == 'square':
        return square
    elif type == 'cube':
        return cube
    else:
        return factorial


# 调用 get_math_func(),程序返回一个嵌套函数
math_func = get_math_func(type='cube')  # 得到 cube函数
print(math_func(3))
math_func = get_math_func(type='square')    # 得到 square函数
print(math_func(4))
math_func = get_math_func(type='other')     # 得到 factorial函数
print(math_func(5))

  

 

推荐阅读