Python小知识点--装饰器
Posted 与你在巅峰相会
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python小知识点--装饰器相关的知识,希望对你有一定的参考价值。
(1)装饰器含参数,被装饰函数不含(含)参数
实例代码如下:
import time # 装饰器函数 def wrapper(func): def done(*args,**kwargs): start_time = time.time() func(*args,**kwargs) stop_time = time.time() print(‘the func run time is %s‘ % (stop_time - start_time)) return done # 被装饰函数1 @wrapper def test1(): time.sleep(1) print("in the test1") # 被装饰函数2 @wrapper def test2(name): #1.test2===>wrapper(test2) 2.test2(name)==dome(name) time.sleep(2) print("in the test2,the arg is %s"%name) # 调用 test1() test2("Hello World")
(2)装饰器含有参数,被装饰函数含(不含)参数
import time user,passwd = ‘admin‘,‘admin‘ 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 passwd == password: print("