Pyhton 装饰器
Posted ray-2019
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pyhton 装饰器相关的知识,希望对你有一定的参考价值。
# -*- coding:utf8 -*-
# Author : Mr·Yang
‘‘‘
装饰器,带参数装饰器,装饰器中带参数
‘‘‘
import time
# 普通装饰器
‘‘‘
def time_decor(func):
def wrapper():
star_time = time.time()
func()
down_time = time.time()
print("总耗时为", down_time - star_time)
return wrapper
@time_decor
def wait():
time.sleep(2)
if __name__ == ‘__main__‘:
wait()
‘‘‘
# 被装饰函数带参数
‘‘‘
def time_decor(func):
def wrapper(name):
star_time = time.time()
func(name)
down_time = time.time()
print("总耗时为", down_time - star_time)
return wrapper
@time_decor
def wait(name):
print("这是{}带参数的装饰器".format(name))
time.sleep(2)
if __name__ == ‘__main__‘:
name = "yanglei"
wait(name)
# 带参数的装饰器
def time_decor(cond):
def external(func):
def wrapper():
if cond == "True":
star_time = time.time()
func()
down_time = time.time()
print("总耗时为", down_time - star_time)
else:
print(" 33[31;1m这是啥也没干的 33[0m")
func()
return wrapper
return external
@time_decor(cond="False")
def wait():
time.sleep(2)
if __name__ == ‘__main__‘:
wait()
# 装饰器和被装饰函数都带参数
def time_decor(cond):
def external(func):
def wrapper(*args, **kwargs):
if cond == "True":
star_time = time.time()
func(*args, **kwargs)
down_time = time.time()
print("总耗时为", down_time - star_time)
else:
print(" 33[31;1m这是啥也没干的 33[0m")
func()
return wrapper
return external
@time_decor(cond="True")
def wait(*args, **kwargs):
print(len(args))
if len(args) > 1:
time.sleep(2)
if args[0]==1:
print(123)
else:
print(args)
if __name__ == ‘__main__‘:
name, age, sun = 1, 2, 3
wait(name, age, sun)
# 被装饰函数带返回值
def time_decor(func):
def wrapper(*args, **kwargs):
if func(*args, **kwargs) == None:
print("没有返回值的函数对象")
else:
print("带返回值的函数对象")
res = func(*args, **kwargs)
return res
return wrapper
@time_decor
def wait(*args, **kwargs):
sun = args[0]+args[1]
return sun
if __name__ == ‘__main__‘:
x = 111
y = 222
a = wait(x,y)
print(a)
‘‘‘
#
def time_decor(func):
def wrapper():
start_time = time.time()
func()
down_time = time.time()
return wrapper
import threading
import time
def time_out(timer):
‘‘‘
一个规定函数执行时间的装饰器
:param timer:
:return:
‘‘‘
def wrapper(func):
def __wrapper():
start_time = time.time()
# 通过设置守护线程强制规定函数的运行时间
t = threading.Thread(target=func)
t.setDaemon(True)
t.start()
time.sleep(timer)
if t.is_alive():
# 若在规定的运行时间未结束守护进程,则主动抛出异常
raise Exception(‘Function execution timeout‘)
print (time.time()-start_time)
return __wrapper
return wrapper
@time_out(50)
def timer():
time.sleep(10)
timer()
以上是关于Pyhton 装饰器的主要内容,如果未能解决你的问题,请参考以下文章