码迷,mamicode.com
首页 > 其他好文 > 详细

【Pyhton 】 装饰器

时间:2020-01-17 18:43:13      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:targe   线程   timer   pre   ISE   exception   timeout   异常   als   

# -*- 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("\033[31;1m这是啥也没干的\033[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("\033[31;1m这是啥也没干的\033[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 】 装饰器

标签:targe   线程   timer   pre   ISE   exception   timeout   异常   als   

原文地址:https://www.cnblogs.com/Ray-2019/p/12206991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!