python 装饰器
2021-03-06 08:29
标签:out == gre cal port col 完成 com int 在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。 用函数decorator装饰function_requiring_decoration函数 以上代码的简写 结果 结果,如上代码就完成了一个类装饰器的功能,给运行的函数添加了时间日志 python 装饰器 标签:out == gre cal port col 完成 com int 原文地址:https://www.cnblogs.com/AntonioSu/p/14304832.html一、函数装饰器
1.从函数中返回函数
def hi(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet
else:
return welcome
a = hi()
print(a)
#outputs:
2.装饰器
import time
def decorator(func):
def decorator_function():
localtime = time.asctime(time.localtime(time.time()))
print(‘before decorator running,time is‘, localtime)
func()
localtime = time.asctime(time.localtime(time.time()))
print(‘after decorator running,time is ‘, localtime)
#必须返回函数名,不带括号
return decorator_function
def function_requiring_decoration():
a, b = 5, 3
time.sleep(1)
print("The result is ", a + b)
function__decoration = decorator(function_requiring_decoration)
if __name__=="__main__":
function__decoration()
import time
def decorator(func):
def decorator_function():
localtime = time.asctime(time.localtime(time.time()))
print(‘before decorator running,time is‘, localtime)
func()
localtime = time.asctime(time.localtime(time.time()))
print(‘after decorator running,time is ‘, localtime)
#fanhuihans,bujiakuohao
return decorator_function
@decorator
def function_requiring_decoration():
a, b = 5, 3
time.sleep(1)
print("The result is ", a + b)
if __name__=="__main__":
function_requiring_decoration()
before decorator running,time is Wed Jan 20 20:07:03 2021
The result is 8
after decorator running,time is Wed Jan 20 20:07:04 2021
二、类装饰器
import time
class Decorator(object):
def __init__(self, func):
self.func = func
def call(self):
localtime = time.asctime(time.localtime(time.time()))
print (‘before decorator running,time is‘,localtime)
self.func() #run add function
localtime = time.asctime(time.localtime(time.time()))
print (‘after decorator running,time is ‘,localtime)
@Decorator
def add():
a,b=5,3
time.sleep(1)
print ("The result is ",a+b)
if __name__=="__main__":
add.call()
before decorator running,time is Wed Jan 20 19:58:41 2021
The result is 8
after decorator running,time is Wed Jan 20 19:58:42 2021