函数式编程

函数过程

过滤: filter() ---> 映射: map() ---> 归约: reduce()

  • 在Python中函数是一等对象(一等公民):

    1. 函数可以赋值给变量
    2. 函数可以做为函数的参数
    3. 函数可以作为函数的返回值 --->装饰器
  • 编程范式(编程理念)

    • 指令式编程(汇编语言)/过程式编程(C语言)
    • Python即支持面向对象, 又支持函数式编程
  • reduce的用法
    python 3.0以后, reduce已经不在built-in function里了, 要用它就得from functools import reduce.
    reduce(function, sequence[, initial]) -> value
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5). If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    意思就是对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素, 以后把前一次调用的结果和sequence的下一个元素传递给function. 如果给出initial, 则第一次传递initial和sequence的第一个元素给function.

functools.reduce(lambda x, y: x * y, range(1, 6))

自定义装饰器 - 修饰函数/装饰类 - 设计模式(代理模式)
代理模式 -
用代理 对象(装饰器函数)去执行被代理对象(被装饰的函数)的行为
面向切面编程 - AOP
程序中跟正常业务逻辑没有必然联系而且会重复使用的功能通常被称为横切关注功能, 这种横切关注功能不应该卸载业务逻辑代码上, 而应该使用装饰器或中间件来完成

装饰器
# 计算函数执行时间的装饰器
def decorate(func):

    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time()
        ret_value = func(*args, **kwargs):
        print(func.__name__, time() - start)
        return ret_value
    return wrapper

# 带参数的装饰器
def record_time(output):

    def decorate(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time()
            ret_value = func(*args, **kwargs):
            output(func.__name__, time() - start)
            return ret_value

        return wrapper

    return decorate


# 装饰器的其他写法
class RecordTime(object):
    def __init__(self, output):
        self.output = output

    def __call__(self, func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time()
            ret_value = func(*args, **kwargs)
            output(func.__name__, time() - start)
            return ret_value
        
        return wrapper

你可能感兴趣的:(函数式编程)