python进阶-09-函数式编程

2020-09-23  本文已影响0人  西海岸虎皮猫大人
'''
变量可以执行函数
函数名也是变量
'''

# 指向函数调用
# print(abs)
# 函数赋给变量
# f = abs
# print(f(-1))

# 函数指向变量
# abs = 10
# 报错
# print(abs(-10))

# 函数可以接受函数作为参数,即高阶函数
# 这种高度抽象的编程范式即函数式编程
# def add(x, y, f):
#     return f(x) + f(y)
#
# print(add(-10, 5, abs))

# 内建高阶函数有map reduce filter sort

# 函数 | 可迭代对象 作为参数
# 原始写法
# a = [1, 2, 3, 4, 5]
# def f(x):
#     return x * x
# result_list = []
# for i in a:
#     result_list.append(f(i))
# print(result_list)

# 返回一个可迭代对象
# it = map(f, a)
# print(type(it))

# 废弃写法
# DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
#   from collections import Iterator
# from collections import Iterator
# 判断是否是可迭代对象
# print(isinstance(it, Iterator))
# print(list(it))

# 数字转字符串
# a = 10
# s = str(a)

# 列表转字符串
# a = [1, 2, 3, 4, 5]
# l = map(str, a)
# print(list(l))

# map传递多个列表
# a = [1, 2, 3, 4]
# b = [10, 20, 30, 40]
# def f(x, y):
#     return x + y
#
# l = map(f, a, b)
# print(list(l))


# reduce
# 序列求和(累加)
a = [1, 2, 3, 4, 5]
# 原始写法
# sum = 0
# for i in a:
#     sum += i
# print(sum)

from functools import reduce
# def sum_test(x, y):
#     return x + y
# # 计算结果做为下一个参数
# sum = reduce(sum_test, a)
# print(sum)

# 列表转拼接数字
# def fn(x, y):
#     return x * 10 + y
#
# 效果 f(f(f(x1, x2), x3), x4)
# a = reduce(fn, [1, 3, 5, 7, 9])
# print(a)

# filter true false
# def is_odd(n):
#     return n % 2 == 1

# 过滤掉偶数
# l = filter(is_odd, [1, 2, 3, 4, 5])
# print(list(l))

# 过滤空字符串
# def not_empty(s):
#     # 空格一起过滤
#     return s and s.strip()
#
# a = ['A', '', 'B', None, 'C', ' ']
# l = filter(not_empty, a)
# print(list(l))


# sorted 排序
# 内置sorted函数可以对列表排序
# 什么算法? 跟踪函数实现 todo
# l = sorted([1, 3, 2, 4, 0])
# print(list(l))
# 逆序 reverse参数
# rl = sorted([1, 3, 2, 4, 0], reversed = True)
# print(list(rl))
# 字符串排序 按照ascii顺序 大写在前
# sl = sorted(['abc', 'ABC', 'D', "s", 'C'])
# print(sl)
# 字符串逆序
# sr = sorted(['abc', 'ABC', 'D', "s", 'C'], reverse = True)
# print(sr)

# sorted是高阶函数, 可以自定义排序函数
# 按照绝对值排序
# l = sorted([1, -2, 3, -4, 5], key=abs)
# print(l)
# 字符串忽略大小写
# sl = sorted(['abc', 'ad', 'ABC', 'D', 'C'], reverse=True, key=str.lower)
# print(sl)

# lambda
# f = lambda a,b,c:a+b+c
# print(f(1, 2, 3))

# 匿名函数实现x*x
# l = map(lambda x:x*x, [1, 2, 3, 4, 5])
# print(list(l))

# sorted对自定义对象排序
# class Student:
#     def __init__(self, name, age):
#         self.name = name
#         self.age = age
#
# s1 = Student('Vincent', 18)
# s2 = Student('Zhangsan', 80)
# s3 = Student('Lisi', 28)
# 指定排序规则
# r = sorted([s1, s2, s3], key=lambda x:x.age)
# 按照姓名逆序
# r = sorted([s1, s2, s3], key=lambda x: x.name, reverse=True)
# for s in r:
#     print(s.name)

# 闭包
# 1.要有函数嵌套 外部函数 内部函数
# 2.内部函数使用外部函数的变量
# 3.外部函数要有返回值
# 闭包为装饰器做铺垫
# 求两个数的和
# 内存泄露??
# def sum(a, b):
#     return a + b
#
# def fun_out(num1):
#     def fun_in(num2):
#         # 内部函数修改外部变量
#         nonlocal num1
#         num1 = 300
#         return num2 + num1
#     # 外部函数返回的是内部函数函数名
#     return fun_in
# f = fun_out(100)
# print(f(200))
# 函数嵌套自身是否可以实现递归?

# 闭包求两点间距离
# import math
# 原始写法
# def get_dis(x1, y1, x2, y2):
#     return math.sqrt((x1-x2)**2 + (y1-y2)**2)
#
# d = get_dis(1, 1, 0, 0)
# print(d)

# 使用闭包
# def get_dis_out(x1, y1):
#     def get_dis_in(x2, y2):
#         return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
#     return get_dis_in
# # 外部函数返回内部函数
# fun_in = get_dis_out(1, 1)
# d = fun_in(2, 2)
# print(d)

# 闭包特殊用途
# 不修改源代码的情况下添加新功能
# 添加日志输出信息
# def fun1():
#     # write_log(fun1)
#     print("fun1")
# def fun2():
#     # write_log(fun1)
#     print("fun2")
#
import time
# def write_log(func):
#     try:
#         file = open('write_log.txt', 'a', encoding='utf-8')
#         # 文件中写入日志信息 方法名 时间
#         file.write('访问: {}'.format(func.__name__))
#         file.write('\t');
#         file.write('时间: {}'.format(time.asctime()))
#         file.write('\n')
#     except Exception as e:
#         print(e.args)
#     finally:
#         file.close();
#
# def fun_out(func):
#     def fun_in():
#         write_log(func)
#         func()
#     return fun_in

# 非侵入
# fun1 = fun_out(fun1)
# fun1()
# fun2 = fun_out(fun2)
# fun2()

# 装饰器 不修改源代码添加功能
# 装饰器简化闭包
# def fun_out(func):
#     def fun_in():
#         write_log(func)
#         func()
#     return fun_in
#
# # fun1作为fun2的参数
# # 类似spring aop
# @fun_out
# def fun1():
#     print('fun1')
#
# @fun_out
# def fun2():
#     print('fun2')
#
# def write_log(func):
#     try:
#         file = open('log.txt', 'a', encoding='utf-8')
#         file.write(func.__name__)
#         file.write('\t')
#         file.write(time.asctime())
#         file.write('\n')
#     except Exception as e:
#         print(e.args)
#     finally:
#         file.close()
#
# fun1()
# fun2()


# 装饰器练习 多个装饰器
# 调用前输出 I am foo
# def fun_out_out(func):
#     def fun_in():
#         print('I am foo2')
#         func()
#     return fun_in
#
# def fun_out(func):
#     def fun_in():
#         print('I am foo')
#         func()
#     return fun_in
#
# # 多个装饰器,自下而上依次装饰
# @fun_out_out
# @fun_out
# def foo():
#     print('foo is running...')
#
# foo()
# import time
# 带参装饰器
# def fun1():
#     print('fun1')
#
# def fun2():
#     print('fun2')
#
# def write_log(func):
#     print('方法名:', func.__name__, '\t', time.asctime())
#
# def fun_out(func):
#     def fun_in(x, y):
#         write_log(func)
#         return func(x, y)
#     return fun_in
#
# @fun_out
# def sum(a, b):
#     return a + b
#
# result = sum(1, 2)
# print(result)


# 通用装饰器
# 参数个数不定 *args可变参数
# import time
# def fun_out(func):
#     # 可以传字典参数
#     def fun_in(*args, **kwargs):
#         write_log(func)
#         return func(*args, **kwargs)
#     return fun_in
# @fun_out
# def sum(a, b):
#     return a + b
# @fun_out
# def add(a, b, c):
#     return a + b + c
#
# def write_log(func):
#     print('访问方法名: ', func.__name__, '\t 时间: ', time.asctime())
# result = sum(1, 2)
# print(result)
# result = add(1, 2, 3)
# print(result)

# 偏函数
# 函数固定属性 偏导数?
# print(int('12345'))
# 8进制
# print(int('12345', base=8))
# 16进制
# print(int('12345', 16))
# 二进制转换 如果书写多次base=2太麻烦
# print(int('1010', base=2))

# def new_int(s):
#     # 只写一次
#     return int(s, base=2)
#
# print(new_int('1010'))


from functools import partial
# 固定参数(设置默认值)
new_int = partial(int, base=2)
print(new_int('1010'))
上一篇下一篇

猜你喜欢

热点阅读