PY3 基础 day4(continue0)

本节内容

1.迭代器&生成器 

2装饰器

3json&pickles数据序列化 

4ATM开发

2装饰器:本质是函数;(装饰其他函数)就是为其他函数添加附加功能;

3原则:1不能修改被装饰的函数代码;2不能修改被装饰函数的调用方式;

 装饰器一个简单的例子

import time
def timmer(func):
    def warpper(*args,**Kwargs):
        start_time = time.time()
        func()
        stop_time = time.time()
        print('the func run time is %s' %(stop_time-start_time))
    return warpper

@timmer
def test1():
    time.sleep(3)
运行结果:

实现装饰器的知识储备:

1函数即变量;2高阶函数;3:嵌套函数;(高阶函数+嵌套函数》=装饰器)

高阶函数:a:把一个函数名当做实参传给另外一个函数;b:返回值中包含函数名;

例子

import time
def timer(func): #timer(test1) func-test1
    def deco():
        start_time = time.time()
        func()
        stop_time = time.time()
        print("the func run time is %s" %(stop_time - start_time))
    return deco

#def timer():
    #def deco():
        #pass
@timer #test1-timer(test1)
def test1():
    time.sleep(3)
    print('in the test1')
@timer
def test2():
    time.sleep(3)
    print('in the test2')
test1()
test2()

升级版装饰器

import time
def timer(func): #timer(test1) func-test1
    def deco(*arg,**kwargs):
        start_time = time.time()
        func(*arg,**kwargs)
        stop_time = time.time()
        print("the func run time is %s" %(stop_time - start_time))
    return deco
@timer #test1-timer(test1)
def test1():
    time.sleep(1)
    print('in the test1')
@timer
def test2(name,age):
    time.sleep(3)
    print('test2',name,age)
test1()
test2("zhang",22)
 
 
装饰器升级版
import time
user = 'zhang'
password = '12345'
def auth(func):
    def wrapper(*args,**Kwargs):
        Username = input("Username:").strip()
        Password = input("Password:").strip()

        if user==Username and password==Password:
            print("\033[32;1mUser has passed authentication\033[0m")
            func(*args,**Kwargs)
        else:
            exit("\033[31;1mInvalid username or password\033[0m")
    return wrapper
def index():
    print("welcome to index page")
@auth
def home():
    print("welcome to home page")
@auth
def bbs():
    print("welcome to bbs page")
index()
home()

升级版

import time
user = 'zhang'
password = '12345'
def auth(auth_type):
    print("auth func:",auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **Kwargs):
            print("wrapper func args:",*args,**Kwargs)
            if auth_type == "local":
                Username = input("Username:").strip()
                Password = input("Password:").strip()
                if user == Username and password == Password:
                    print("\033[32;1mUser has passed authentication\033[0m")
                    res = func(*args, **Kwargs)  # from home
                    print("----after authentication")
                    return res
                else:
                    exit("\033[31;1mInvalid username or password\033[0m")
            elif auth_type == "ldap":
                print("搞什么,不会啊!!!")

        return wrapper
    return outer_wrapper

def index():
    print("welcome to index page")
@auth(auth_type="local")
def home(): #home = auth()
    print("welcome to home page")
    return "from home"
@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs page")
    return "from bbs"
index()
home()
bbs()


1,迭代器和生成器

生成器:只有在调用时才会生成相应的数据,只记录当前的位置,只有一个——next——方法。next()

(i*i for i in range(10))

 
 

菲波那切数列:

def fib(max):
    n,a,b = 0,0,1
    while n < max:
        print(b)
        a,b = b,a+b
        n=n+1
    return 'donc'
fib(10)
生成器
def fib(max):
    n,a,b = 0,0,1
    while n < max:
        #print(b)
        yield (b)
        a,b = b,a+b
        n=n+1
    return 'done'
print(fib(10))

升级版

def fib(max):

    n,a,b = 0,0,1
    while n < max:
        #print(b)
        yield b
        a,b = b,a+b
        n=n+1
    return 'done'
#print(fib(10))
f=fib(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print("---循环---")
for i in f:
    print(i)
判断出错在
 
 
while True:
    try:
        x=next(g)
        print('g:',x)
    except StopAsyncIteration as e:
        print('Generator return value:',e.value)
         break

生成器并行

import time

def consumer(name):
    print("%s 准备吃包子了!!"%name)
    while True:
        baozi=yield

        print("包子[%s]来了,被[%s]吃了!"%(baozi,name))

def profucer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("开始准备包子了!")
    for i in range (10):
        time.sleep(1)
        print("做了两个包子!")
        c.send(i)
        c2.send(i)
profucer("zhang")
内置方法
abs 取绝对值;all()所有为真才为真;any()一个为真就为真;

    ascii();bin()二进制转换;class bool()布尔值;

     calss byterray([[][]])字节数组(字符串变数组改二进制);

    callable(object)是否可以调用;chr(i)转换为asiic;与ord相反;

    classmethod()类方法;compile()编译代码==exec;complex()复数;

    dict()字典;dir()查方法;divmod(a,b)商,余数;

    eval(,,,)字符串变字典;exec();

     filter()过滤;   map();

res = (filter(lambda n:n>5,range(10)))

for i in res:
    print(i)
 
 
res = map(lambda n:n*n,range(10))#[i*2 for i in range(10]
for i in res:
    print(i)

隐函数

cacl = lambda n:print(n)

cacl(5)
import functools
res = functools.reduce(lambda x,y:x+y,range(10))
print(res)
 
 

frozenset([])冻结;getattr()面向对象介绍;

globals();     hash(object)自动生成数据的映射关系

hex()转成16进制;ID();len()长度;

def test():
    local_var = 333
    print('locals')
test()
print(globals())
print(globals().get('local_var'))
 
 
max();min();  next();

python一切皆对象;

oct()转8进制;pow(3,5)3的5次方;round(1.33434,3)保留3位;

slice()切片;sorted()排序;sum;zip();

a=[1,2,3,4]

b=['a','b','c','d']
for i in zip(a,b):
    print(i)
 
 
import()
json&pickles数据序列化 

json序列化

import json
info = {
    'name':'alex',
    'age':22
}
f = open("test.text","wb")
f.write(json.dumps(info))
#print(json.dumps(info))
f.close()
json反序列化
 
 
import pickle
f = open("test.text","rb")

data = pickle.loads(f.read())
print(data)

pickle(),功能与json,相同;可以处理更复杂的内容;

python 规范化设置





    

 
 
 
 
 






猜你喜欢

转载自blog.csdn.net/qq_37951246/article/details/80412419
今日推荐