python-装饰器

1.匿名函数:没有函数名称,--  赋值给一个变量 就可以

calc=lambda x:x*3
calc=calc(3)
print(calc)
#------
g=map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(g)
2.列表生成式
l= (i*2 for i in range(10))
print (l.__next__())# 取值
print (l.__next__())# 取值

3.斐波那契数列

def fib(max):
    n,a,b =0,0,1
    while n<max:
        yield b
        a,b =b,a+b
        n+=1
    return 'done' # next 取Return的值
res=fib(5)
while True:
    try :
        x=next(res)
        print ('res:',x)
    except StopIteration as e:
        print ('generator return value',e.value)
        break
4.高阶函数 
特性 1.某一函数当做参数传入另一个函数中 2.函数的返回值包含n个函数,n>0
def bar():
    print( 'in the bar')
def test(func):
    print(func)
    res=func()
    return res #返回内存地址
test(bar)

#嵌套函数
def foo():
    print('in the foo')
    def bar():
        print('in the bar')
    bar()
foo()

#局部作用域与全局作用域的访问顺序
def foo():
    x=1
    def bar():
        x=2
        def test():
            x=3
            print(x)
        test()
    bar()
foo()

5.装饰器,本质是函数,就是为其人函数添加附加功能,不能修改装饰函数的代码和调用方式。
#装饰器=高阶函数+嵌套函数

import time
def timer(func):#timer(test1)
    def deco():
        start_time=time.time()
        func()
        stop_time=time.time()
        print('the func run time%s:'%(stop_time-start_time))
    return deco
@timer
def test1():
    print ('in the test1')
    time.sleep(1)
@timer
def test2():
    print('in the test2')
    time.sleep(1)

test1()
test2()

6.通过yield实现在单线程的情况下实现并发运算的效果

__author__ = 'fulimei'

import time
def consumer(name):
    print ("%s准备吃包子啦! "%name)
    while True:
        baozi= yield
        print("包子%s来了,被%s吃了"%(baozi,name))

def product(name):
    c=consumer('zhangsan')
    c1 = consumer('lisi')
    c.__next__()
    c1.__next__()
    b1="韭菜"
    c.send(b1)
    print("开始准备做包子啦")
    for i in range(3):
        time.sleep(0.1)
        c.send(i)
        c1.send(i)
product("fulimei")

7.字典格式写入文件中或从文件中读取数据

info ={
    'user':'fulimei',
    'password':'asd123',
}
f=open("test.txt",'w')
f.write(str(info))
f.close()

#-----读取文件的数据
f=open("test.txt",'r')
data=eval(f.read())
print(data)
f.close()
print(data['password'])

8.字典格式写入文件中或从文件中读取数据---用json实现

#json序列化-将字典格式的呢日写入文件中
import json
info ={
    'user':'fulimei',
    'password':'asd123',
}
f=open("test.txt",'w')
f.write(json.dumps(info))
f.close()


#序列化,将文件中的内容读取出来
import json
f=open("test.txt",'r')
data=json.loads(f.read())
print(data)
f.close()
print(data['password'])

#反序列号的读文件内容
import pickle
f=open("test1.txt","rb")
data=pickle.loads(f.read())
print(data)
print(data['age'])
f.close()
原文地址:https://www.cnblogs.com/xuehuahongmei/p/5786183.html