函数 装饰器
什么是裝飾器
為被裝飾器對象添加額外功能的一種工具
為什么用裝飾器
軟件維護中應該遵從開放封閉的原則
封閉源代碼,對程序的擴展是開放的
1、不改變程序的源代碼
2、不改變程序的調用方式
如何用裝飾器
1、無參裝飾器
運行一個程序,裝飾上一個程序運行了幾秒鐘的工具
import time def index():print('welcom to index')time.sleep(3)def timmer(func):def wrapper(*args, **kwargs):start = time.time()func(*args, **kwargs)stop = time.time()print('run time is %s' % (stop - start))return wrapperindex=timmer(index) index()補充:
@加裝飾器的變量名 可以直接省略 這個步驟
index=timmer(index)裝飾器固定套路
def deco(func):def wrapper(*args,**kwargs):res=func(*args,**kwargs)return resreturn wrapper2、有參裝飾器
我們可以從固定套路中看出 函數 deco 和func 參數都已經固定死了。如果需要為函數里面傳參的話,我么只能在deco函數外面又套一個函數 ,進行傳參。
import timecurrent_user = {'urse': None}def auth(engine='file'):def deco(func):def wrapper(*args, **kwargs):if current_user['urse']:res = func(*args, **kwargs)return resuser = input('username>>:')pwd = input('password>>:')if engine == 'file':if user == 'egon' and pwd == '123':print('login successful')current_user['urse'] = userres = func(*args, **kwargs)return reselse:print('user or pqssword error')elif engine == 'mysql':print('基于mysql的認證')elif engine == 'ldap':print('基于ldap的認證')else:print('無法識別認證來源')return wrapperreturn deco@auth() def index():print('welcome to index page')time.sleep(1)@auth() def home(name):print('welcome %s to home page' % name)time.sleep(1)index() home('egon')?
轉載于:https://www.cnblogs.com/zuozhengjun/p/9173903.html
總結
- 上一篇: C++使用GDI+实现图片格式转换
- 下一篇: 记一次对 Laravel-permiss