首页 > 编程语言 > 详细

python中初级装饰器总结

时间:2018-07-19 00:32:03      阅读:277      评论:0      收藏:0      [点我收藏+]

打印 args 与 *args 的区别

1 #打印时区别
2 def outer(*args, **kwargs):
3     print(args)         #输出结果:(1, 2, 3, 4)
4     print(*args)        #输出结果:1 2 3 4
5 
6 outer(1,2,3,4)
 1 #函数调用时区别
 2 def outer(*args, **kwargs):
 3     print(args)
 4     print(*args)        #也是调用函数,调用的是print函数
 5 
 6 outer([1,2,3,4])        #输出结果:([1, 2, 3, 4],)
 7                         #          [1, 2, 3, 4]
 8 
 9 outer(*[1,2,3,4])        #输出结果:(1, 2, 3, 4)
10                         #           1 2 3 4
11                         #等价于outer(1,2,3,4),以及outer(*(1,2,3,4))

规律

 1 def outer(*args, **kwargs):
 2     print(args)
 3     print(*args)        #也是调用函数,调用的是print函数
 4     def inner(*args):
 5         print(inner:,args)
 6     inner(*args)
 7 
 8 outer(1,2,3,4)            #输出结果:(1, 2, 3, 4)
 9 #                         #           1 2 3 4
10 #                         #           inner: (1, 2, 3, 4)    在被传参时聚合

总体

技术分享图片

def wrapper(func):
    def inner(*args,**kwargs):
        print(在被装饰的函数执行之前做的事)
        ret = func(*args,**kwargs)
        print(在被装饰的函数执行之后做的事)
        return ret
    return inner

@wrapper
def func(day):
    print(python目前是排名第{}的语言.format(day))
    return 所以我们一定要坚持学习python

ret = func(4)
print(ret)

 

python中初级装饰器总结

原文:https://www.cnblogs.com/rcat/p/9333509.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!