Python高级语法:lambda、map、filter、reduce、yeild、闭包、装饰器、异步协程

整体思维导图

1、变量赋值

2、容器序列的深浅拷贝

3、字典与collections扩展内置数据类型

4、函数调用

5、变量作用域(命名空间)

6、高阶函数

7、闭包、装饰器

8、对象协议与鸭子类型

9、yield语句

10、异步协程

在这里插入图片描述

代码示例

  1. 例子1
"""
计算三维点的欧氏距离
"""
# 方法一:利用numpy库
import numpy as np

vector1 = np.array([1,2,3])
vector2 = np.array([4,5,6])

op1 = np.sqrt(np.sum(np.square(vector1-vector2)))
op2 = np.linalg.norm(vector1-vector2)
print(f'op1:{op1},op2:{op2}')

# 方法二:利用nametuple
from collections import namedtuple
from math import sqrt

Point = namedtuple('Point',['x','y','z'])

class Vector(Point):
    def __init__(self,p1,p2,p3):
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3
    # 重构a-b的魔术方法
    def __sub__(self, other):
        tmp = (self.p1-other.p1)**2 + (self.p2-other.p2)**2 + (self.p3-other.p3)**2
        return sqrt(tmp)

p1 = Vector(1,2,3)
p2 = Vector(4,5,6)
print (p1-p2)

2.例子2

# lambda
# def k(x):
#     return x+1

k = lambda x : x +1
print (k(1))


# map
def square(x):
    return x**2

m = map(square,range(5))
print(next(m))
print (next(m))
print(list(m))

# 推导式
li = [square(x) for x in range(5)]
print (li)

# reduce
from functools import reduce
def add(x,y):
    return x+y

ad = reduce(add,[0,1,2,3,4,5,6,7,8,9,10])
print(ad)

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

li = list(filter(is_odd,[1,2,3,4,5,6]))
print (li)

# 偏函数
def add(x,y):
    return x+y

from functools import partial
add_2 = partial(add,1)
res = add_2(9)
print (res)

3.例子3

# 装饰器在模块导入的时候自动运行
def decorate(func):
    print ('running...')
    def inner():
        return func()
    return inner

@decorate
def func2():
    pass

4.例子4

# 包装
def html(func):
    def decorate():
        return f'<html>{func()}</html>'
    return decorate

def body(func):
    def decorate():
        return f'<body>{func()}</body>'
    return decorate

@html
@body
def content():
    return 'hello world'

con = content()
print (con)

5.例子5

"""
例子5
"""

# 被修饰函数带参数
def outer(func):
    def inner(a,b):
        print (f'inner:{func.__name__}')
        print (a,b)
        func(a,b)
    return inner

@outer
def foo(a,b):
    print (a+b)
    print (f'foo:{foo.__name__}')

foo(1,2)
foo.__name__

# 被修饰函数带不定长参数
def outer2(func):
    def inner2(*args,**kwargs):
        func(*args,**kwargs)
    return inner2

@outer2
def foo2(a,b,c):
    print (a+b+c)

foo2(1,2,3)

# 被修饰函数带返回值
def outer3(func):
    def inner3(*args,**kwargs):
        ##
        ret = func(*args,**kwargs)
        ##
        return ret
    return inner3

@outer3
def foo3(a,b,c):
    return (a+b+c)

r = foo3(1,1,3)
print (r)

# 装饰器带参数
def outer_arg(bar):
    def outer(func):
        def inner(*args,**kwargs):
            ret = func(*args,**kwargs)
            print (bar)
            return ret
        return inner
    return outer

@outer_arg('foo_arg')
def foo(a,b,c):
    return (a+b+c)
print (foo(1,1,1))

#装饰器堆叠 注意顺序

6.例子6

"""
例子6
"""
class Foo(object):
    # 用于方法返回
    def __str__(self):
        return '__str__ is called'

    # 用于字典操作
    def __getitem__(self, key):
        print (f'__getitem__ {key}')

    def __setitem__(self, key, value):
        print (f'__setitem__ {key},{value}')

    def __delitem__(self, key):
        print (f'__delitem__ {key}')

    # 用于迭代
    def __iter__(self):
        return iter([i for i in range(5)])

bar = Foo()
print (bar)

bar['key1']
bar['key1'] = 'value1'
del bar['key1']

for i in bar:
    print (i)

7.例子7

""""
例子7
"""
# itertools的三个常见无限迭代器
import itertools

#计数器
count = itertools.count()
next(count)
next(count)
next(count)

# 循环遍历
cycle = itertools.cycle(('yes','no'))
next(cycle)
next(cycle)
next(cycle)

# 重复
repeat = itertools.repeat(10,times=2)
next(repeat)
# next(repeat)
# next(repeat)

8.例子8

""""
例子8
"""
def jumping_range(up_to):
    index = 0
    while index < up_to:
        jump = yield index
        print (f'jump is {jump}')
        if jump is None:
            jump = 1  # next()或者send(None)
        index += 1
        print (f'index is {index}')

iterator = jumping_range(5)
print (next(iterator)) # 0
print (iterator.send(2)) # 2
print (next(iterator)) # 3
print (iterator.send(-1)) # 2
for x in iterator:
    print (x) # 3

9.例子9

"""
例子9

await接收的对象必须是awaitable对象
awaitable对象定义了__await__()方法
awaitable对象有三类:1、协程 coroutine 2、任务 Task 3、未来对象 Future
"""
import asyncio
async def main():
    print ('hello')
    await asyncio.sleep(3)
    print ('world')

asyncio.run(main())

10.例子10

# 例子10
## 协程asyncio与进程池multiprocessing
from multiprocessing import Pool
import asyncio
import time

async def test(time):
    await asyncio.sleep(time)

async def main(num):
    start_time = time.time()
    tasks = [asyncio.create_task(test(1)) for proxy in range(num)]
    [await t for t in tasks]
    print (time.time() - start_time)

def run(num):
    asyncio.run(main(num))

if __name__ == '__main__':
    start_time = time.time()
    p = Pool()
    for i in range(4):
        p.apply_async(run,args=(2500,))
    p.close()
    p.join()
    print (f'total {time.time()-start_time}')

异步携程参考链接:https://www.cnblogs.com/lfywork/p/14850871.html

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值