最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

python 装饰器 part2

XAMPP新闻 admin 854浏览 0评论

python 装饰器
传参
被装饰的函数带有参数的情况
接上一篇,直接上代码

import time
def decorator(func):
def process(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(‘函数func(也就是被装饰的函数)的运行时间是:{}’.format(end-start))
return process

@decorator # python 装饰器的正确使用,不需要传参
def decorated():
time.sleep()
print(‘decorated function’)

@decorator # python 装饰器的正确使用,需要传参
def decorated(key, val):
time.sleep()
print(‘decorated function’)

# 此时不用再像上面一样赋值,可以直接调用
decorated()
decorated(key, val)
</python>

返回值
被装饰的函数有返回值在装饰器内部需return被装饰函数的调用
代码:

import time
def decorator(func):
def process(*args, **kwargs):
start = time.time()
return func(*args, **kwargs)
# end = time.time()
# print(‘函数func(也就是被装饰的函数)的运行时间是:{}’.format(end-start))
return process

@decorator # python 装饰器的正确使用,不需要传参
def decorated():
time.sleep()
print(‘decorated function’)
return ‘来自不带参数的被装饰函数’

@decorator # python 装饰器的正确使用,需要传参
def decorated(key, val):
time.sleep()
print(‘decorated function’)
return ‘来自带有参数的被装饰函数’

# 此时不用再像上面一样赋值,可以直接调用
decorated()
decorated(key, val)
装饰器带参数
@decorator(val=”)
需要对装饰期代码再包装一层

代码

import time
def warpper(val_type):
def decorator(func):
def process(*args, **kwargs):
start = time.time()
return func(*args, **kwargs)
return process
return decorator

@decorator(val_type=”) # python 装饰器的正确使用,不需要传参
def decorated():
time.sleep()
print(‘decorated function’)
return ‘来自不带参数的被装饰函数’

@decorator(val_type=”) # python 装饰器的正确使用,需要传参
def decorated(key, val):
time.sleep()
print(‘decorated function’)
return ‘来自带有参数的被装饰函数’

# 此时不用再像上面一样赋值,可以直接调用
decorated()
decorated(key, val)

转载请注明:XAMPP中文组官网 » python 装饰器 part2

您必须 登录 才能发表评论!