python装饰器返回参数_Python装饰器

无返回值的装饰器:

importtimedef timer(func): #无返回值装饰器

def test_extra(*args, **kwargs): #传入参数长度可变(参数多少都可用)

start_time = time.time() #装饰器添加功能:计时

func(*args, **kwargs) #执行原函数功能

end_time =time.time()print("The func has run for %s s\n" % (end_time -start_time))return test_extra #返回的是test_extra的内存地址,不是test_extra的运行结果

@timer#text1 = timer(text1)

def test(): #原函数不需要参数

time.sleep(1)print("This is test1.")

test()#调用方式不变

输出结果:

This is test1.

The func has run for 1.000288248062134 s

def timer(func): #无返回值装饰器

def test_extra(*args, **kwargs): #传入参数长度可变(参数多少都可用)

start_time = time.time() #装饰器添加功能:计时

func(*args, **kwargs) #执行原函数功能

end_time =time.time()print("The func has run for %s s\n" % (end_time -start_time))return test_extra #返回的是test_extra的内存地址,不是test_extra的运行结果

@timerdef test(name, age): #原函数需要参数

print("In the test2")

time.sleep(2)print("Your name is" + name +age)

test("name", "1") #调用方式不变

输出结果:

In the test2

Your name isname1

The func has run for 2.0002686977386475 s

有返回值的装饰器:

importtimedef timer(func): #有返回值的装饰器

def test_extra(*args, **kwargs): #传入参数长度可变(参数多少都可用)

start_time = time.time() #装饰器添加功能:计时

res = func(*args, **kwargs) #获得func函数的返回值

end_time =time.time()print("The func has run for %s s\n" % (end_time -start_time))return res #返回原函数的返回值

return test_extra #返回的是test_extra的内存地址,不是test_extra的运行结果

@timerdeftest(content):print("In the test")

time.sleep(2)print(content)return "This is return of test"

print(test("666")) #打印出test的返回值

输出结果:

In the test

666

The func has run for 2.0005550384521484 s

This is return of test

和之前的区别只是最内层的函数有了返回值,等于原函数的返回值

可以传给装饰器传一个额外参数的装饰器

importtimedef timer(parameter): #可以传给装饰器传一个额外的参数的装饰器

deftimer_in(func):def test_extra(*args, **kwargs): #传入参数长度可变(参数多少都可用)

print(parameter)

start_time=time.time()

func(*args, **kwargs) #获得func函数的返回值

end_time =time.time()print("The func has run for %s s\n" % (end_time -start_time))return test_extra #返回的是test_extra的内存地址,不是test_extra的运行结果

returntimer_in

@timer(parameter="This is an extra parameter") #给装饰器传入一个参数

deftest(content):

time.sleep(2)print("This is in the test")print(content)

test("666") #打印出test的返回值

输出结果:

This is an extra parameter

This is in the test4

666

The func has run for 2.0006258487701416 s

和之前的区别是又多加了一层函数

小结

装饰器就是先嵌套一层函数添加功能,再嵌套一层函数,这层函数的返回值是里面那一层函数的内存地址

装饰器中函数的返回值不要加括号,传入的是内存地址,不是运行结果

注意:装饰器不能直接用于迭代函数,否则会把装饰器一起迭代,需要使用另一个添加装饰器的函数调用需要装饰的函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值