python 装饰器

  • 修饰器的作用其实就是把会经常调用 (比如:记录程序用时等)的通用功能封装成函数的形式,而避免每次使用的时候重复输入

  • 下面不会赘述概念,直接上例子理解:(如需详细理解,可以看看这个博客哦,以下的例子也是转自该博客)
    1.example 1

    def bread(func) :  
        def wrapper() :  
            print("</'''       '''\>")
            func()  
            print("<\______/>")
        return wrapper  
    
    def ingredients(func) :  
        def wrapper() :  
            print("#tomatoes#")
            func()  
            print("~salad~")
        return wrapper  
    
    @bread  
    @ingredients  
    def sandwich(food="--ham--") :  
        print(food)
    
    sandwich()
    '''
    ouput:
    </'''       '''\>
    #tomatoes#
    --ham--
    ~salad~
    <\______/>
    '''
    

    怎么去理解上面的代码呢?
    首先,找到@,这个就是装饰器标志,后面的函数名就是被装饰的函数的名字
    然后,记住一点就可以了:装饰器的执行是有顺序的,从上到下对应装饰的从外到内,所以的装饰等价于bread(ingredients(sandwich))
    通过output我们可以很清楚的看到,程序是从外到内层层递进的
    2.example 2

    def w2(fun):
        def wrapper(*args,**kwargs):
            print("this is the wrapper head")
            fun(*args,**kwargs)
            print("this is the wrapper end")
        return wrapper
    
    @w2
    def hello(name,name2):
        print("hello"+name+name2)
    
    hello("world",a=3)
    
    '''
    output:
    this is the wrapper head
    helloworld!!!
    this is the wrapper end
    '''
    

3.example 3

def func_args(pre='xiaoqiang'):
    def w_test_log(func):
        def inner():
            print('...记录日志...visitor is %s' % pre)
            func()
        return inner
    return w_test_log

@func_args('wangcai')
def test_log():
    print('this is test log')

test_log()

	'''
	output:
	...记录日志...visitor is wangcai
	this is test log
	'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值