初识python: 装饰器

定义:
  
本质是函数,功能是“装饰”其它函数,即为其他函数添加附加功能
原则:
1、不能修改被装饰函数的源代码;
2、不能修改被装饰函数的调用方式
实现装饰器知识储备:
1、函数即“变量”;
2、高阶函数;
3、嵌套函数。

实例1:初始版
# 定义装饰器函数
import time
def qt_fun(func):
    def gj_func(*args,**kwargs): #关键点,定义不定实参传入值个数*args,形参个数**kwargs
        start_time=time.time()
        func(*args,**kwargs) #关键点,传入参数
        stop_time=time.time()
        print('运行时间:',stop_time-start_time)
    return gj_func #关键点,返回值。

@qt_fun #关键点,引用装饰器,相当于:test1 = qt_fun(test1)
def test1(name):
    time.sleep(1)
    print('姓名:',name)

@qt_fun #关键点,引用装饰器,test2 = qt_fun(test2)  test2()
def test2(name,age,addrs):
    time.sleep(2)
    print('姓名:%s 年龄:%s 地址:%s'%(name,age,addrs))


#test1 = qt_fun(test1)
#test1()

#可替换成 @qt_fun  @装饰器名

#调用函数
test1('simple')
test2('simple',26,'四川')


实例2:终极版

user_name = 'simple'
password = '123'
def choose_type(c_type):
    def login_f(func):
        def in_fun(*args,**kwargs):
            if c_type == 'A':
                print('当前选择的验证方式为:', c_type)
                name=input('用户名:').strip()
                passwd=input('密码:').strip()
                if name==user_name and passwd==password:
                    print('登录成功!')
                    func(*args,**kwargs)
                else:
                    exit('用户名或密码不正确,登录失败!')
            elif c_type == 'B':
                print('当前选择的验证方式为:', c_type)
                print('此验证方式,开发中....')
            else:
                print('输入的验证方式不正确!')
        return in_fun
    return login_f

@choose_type(c_type=input('请选择home的验证方式(A/B):').strip())
def home():
    print('欢迎进入主页!')

@choose_type(c_type=input('请选择bbs的验证方式(A/B):').strip())
def bbs():
    print('欢迎进入bbs界面!')

def index():
    print('欢迎光临index界面!此界面无需验证!')

home()
bbs()
index()

输出结果:

世风之狡诈多端,到底忠厚人颠扑不破; 末俗以繁华相尚,终觉冷淡处趣味弥长。
原文地址:https://www.cnblogs.com/simple-li/p/9743799.html