python学习(十一)——装饰器、解压序列、数字交换

一、装饰器:本质是函数,功能是为其他函数添加附加功能

1、原则:

(1)不修改被修饰函数的源代码

(2)不修改被修饰函数的调用方式

2、实现基础:

装饰器=高阶函数+函数嵌套+闭包

(1)高阶函数的使用

'''
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
'''
#多运行了一次,不合格
def timer(func):
    start_time=time.time()
    func()
    stop_time = time.time()
    print('函数运行时间是  %s' % (stop_time-start_time))
    return func
foo=timer(foo)
foo()


#没有修改被修饰函数的源代码,也没有修改被修饰函数的调用方式,但是也没有为被修饰函数添加新功能
def timer(func):
    start_time=time.time()
    return func
    stop_time = time.time()
    print('函数运行时间是  %s' % (stop_time-start_time))

foo=timer(foo)
foo()

(2)函数嵌套

def foo():
    print('from foo')
    def test():
        pass

(3)闭包

def father(auth_type):
    print('from father包 %s' %auth_type)
    def son():
        print('小包%s' %auth_type)
        def grandson():
            print('小小包%s' %auth_type)
        grandson()

    son()

father('f')

3、装饰器实现:

(1)装饰器框架

def timmer(func): 
    def wrapper():
        res = func()
        return res
    return wrapper

(2)装饰器:为test添加时间计算

import time
def timmer(func): #func=test
    def wrapper():
        start_time=time.time()
        res = func() #就是在运行test()
        stop_time = time.time()
        print('运行时间是%s' %(stop_time-start_time))
        return res
    return wrapper

@timmer 
# test=timmer(test)
def test():
    time.sleep(3)
    print('test函数运行完毕')

# res=timmer(test)  #返回的是wrapper的地址
# res()  #执行的是wrapper()
test()


# 加上参数
import time
def timmer(func): #func=test1
    def wrapper(*args,**kwargs): #test('linhaifeng',age=18)  args=('linhaifeng')  kwargs={'age':18}
        start_time=time.time()
        res=func(*args,**kwargs) #就是在运行test()         func(*('linhaifeng'),**{'age':18})
        stop_time = time.time()
        print('运行时间是%s' %(stop_time-start_time))
        return res
    return wrapper

@timmer
def test1(name,age,gender):
    time.sleep(1)
    print('test1函数运行完毕,名字是【%s】 年龄是【%s】 性别【%s】' %(name,age,gender))
    return '这是test的返回值'

# res=test('linhaifeng',age=18)  #就是在运行wrapper
# # print(res)
# test1('alex',18,'male')

test1('alex',18,'male')

 (3)函数闭包为函数加上认证功能

user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','passwd':'123'},
]
current_dic={'username':None,'login':False}


def auth_func(func):
    def wrapper(*args,**kwargs):
        if current_dic['username'] and current_dic['login']:
            res = func(*args, **kwargs)
            return res
        username=input('用户名:').strip()
        passwd=input('密码:').strip()
        for user_dic in user_list:
            if username == user_dic['name'] and passwd == user_dic['passwd']:
                current_dic['username']=username
                current_dic['login']=True
                res = func(*args, **kwargs)
                return res
        else:
            print('用户名或者密码错误')

    return wrapper

@auth_func
def index():
    print('欢迎来到京东主页')

@auth_func
def home(name):
    print('欢迎回家%s' %name)

@auth_func
def shopping_car(name):
    print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))

print('before-->',current_dic)
index()
print('after--->',current_dic)
home('产品经理')

(4)函数闭包为函数加上认证功能带参

user_list=[
    {'name':'alex','passwd':'123'},
    {'name':'linhaifeng','passwd':'123'},
    {'name':'wupeiqi','passwd':'123'},
    {'name':'yuanhao','passwd':'123'},
]
current_dic={'username':None,'login':False}

def auth(auth_type='filedb'):
    def auth_func(func):
        def wrapper(*args,**kwargs):
            print('认证类型是',auth_type)
            if auth_type == 'filedb':
                if current_dic['username'] and current_dic['login']:
                    res = func(*args, **kwargs)
                    return res
                username=input('用户名:').strip()
                passwd=input('密码:').strip()
                for user_dic in user_list:
                    if username == user_dic['name'] and passwd == user_dic['passwd']:
                        current_dic['username']=username
                        current_dic['login']=True
                        res = func(*args, **kwargs)
                        return res
                else:
                    print('用户名或者密码错误')
            elif auth_type == 'ldap':
                print('鬼才特么会玩')
                res = func(*args, **kwargs)
                return res
            else:
                print('鬼才知道你用的什么认证方式')
                res = func(*args, **kwargs)
                return res

        return wrapper
    return auth_func

@auth(auth_type='filedb') 
# auth_func=auth(auth_type='filedb')-->@auth_func 附加了一个auth_type  --->index=auth_func(index)
def index():
    print('欢迎来到京东主页')

@auth(auth_type='ldap')
def home(name):
    print('欢迎回家%s' %name)
#
@auth(auth_type='sssssss')
def shopping_car(name):
    print('%s的购物车里有[%s,%s,%s]' %(name,'奶茶','妹妹','娃娃'))

# print('before-->',current_dic)
index()
# print('after--->',current_dic)
# home('产品经理')
# shopping_car('产品经理')

二、解压序列

l = [1,2,3,4,5,6,7,8,9,0]   # 只取开始和末尾
a,*_, c = l
print(a,c)

l = [1,2,3,4,5,6,7,8,9,0]   # 只取开始和末尾
a,*_, c = l
print(a,c,_)

三、交换数字

f1 = 1
f2 = 2
f1, f2 = f2, f1
print(f1,f2)

猜你喜欢

转载自blog.csdn.net/qq_28334183/article/details/82828107
今日推荐