初识python: 装饰器
2024-09-07 11:26:33
定义:
本质是函数,功能是“装饰”其它函数,即为其他函数添加附加功能
原则:
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()
输出结果:
最新文章
- 编辑器sublime text3和插件package control、Sidebar Enhancements插件安装
- 【Java基础】方法
- Mybatis在xml文件中处理大于号小于号的方法
- 51nod1537 分解
- HDOJ/HDU 2535 Vote(排序、)
- Visual Prolog 的 Web 专家系统 (6)
- file_get_contents无法请求https连接的解决方法
- Qt Creator编译运行成功,但是显示系统找不到指定的文件(比如urlmon.dll动态链接库)
- ConstraintLayout知识记录
- Vue+Webpack构建移动端京东金融(一、开发前准备)
- Django积木块五——分页
- Xadmin添加,编辑,删除
- laravel中的登录页面逻辑
- datagrid行内编辑时为datetimebox
- Codeforces Round #258 (Div. 2) C. Predict Outcome of the Game 水题
- LeetCode--191--位1的个数
- Docker Compose 部署前后端分离应用
- Lingo 做线性规划 - Marketing Applications
- FORALL用法小结
- 修改 Cloud image 的密码的简单方法