[Python学习笔记] 函数装饰器

函数的调用

定义

def function0():
    print("This is function")

调用

function0()

调用一个函数,“函数名(参数)”,函数名function0只是一个函数的地址指针,真正让函数运行的是后面的()。所以,函数的运行可以看成两个步骤:函数名找到函数,然后加(参数)”运行函数。

函数的函数

def function0():
    print("This is function")

def decorator(fun):
    print("This is decorator")
    return wrap

def wrap():
    print("This is wrap")
    function0()

decorator(function0)()
#== print("This is decorator") + wrap()
#== print("This is decorator") + print("This is wrap")  + function0()
#== print("This is decorator") + print("This is wrap")  + print("This is function")

输出:

This is decorator
This is wrap
This is function

函数装饰器

def decorator(fun):
    def wrap():
        print("This is wrap")
        fun()
    print("This is decorator")
    return wrap

@decorator
def function0():
    print("This is function")

function0()

结果:

This is decorator
This is wrap
This is function

这里

@decorator

就是装饰器,其作用就是相当于:

decorator(function0)()

函数的运行可以分成两个部分:函数名找到函数,然后加(参数)”运行函数。所以对于带装饰器的函数:

@decorator
def function0():
    print("This is function")

运行

function0()

首先是把function0作为参数,通过(function0)运行decorator函数,返回wrap函数名;然后function0()()运行wrap函数。

wrap函数定义到decorator函数内部,这样wrap函数就可以直接利用传递到decorator函数的参数fun(这里就是function0)。

所以,使用装饰器的本质就是,把原函数的地址传递到装饰器里面,在装饰器里面定义新的函数return回来运行,通过在新函数里面定义新的方法和特性,从而增加原函数的功能。同时由于原函数的地址已经传递给装饰器,新函数也可以获得原函数的地址从而输出原函数的全部特性。

上面的例子原函数不含任何参数,对于含有参数的原函数function0(args, kwargs),对wrap进行适当修改即可。上面提到,decorator(function0)返回的是wrap函数名,接着function0(args, kwargs)(args, kwargs)部分则会运行wrap函数,即wrap(args, kwargs)。所以,在定义wrap的时候,将其定义为接收任意数量参数的形式即可(Python函数接收任意数量参数):

def decorator(fun):
    def wrap(*args, **kwargs):
        print("This is wrap")
        fun(*args, **kwargs)
    print("This is decorator")
    return wrap

@decorator
def function0(args, kwargs):
    print("This is function")

function0(args, kwargs)

带参数的装饰器

带参数的装饰器,那就把装饰器的参数单独收集了,然后再收集传入的函数,最后再收集传入函数的参数。

 
# 装饰器带参数,一般都是三层
def first(a):  # 第一层  :负责接收装饰器的参数
    def second(func):   # 第二层  :负责接收函数
        def third(*args, **kwargs):  # 第三层 ,负责接收函数的参数
            func(*args)
            print("----------------------这里是{}FM90.8".format(a))
        return third  # 返出来的是 第三层
    return second   # 返出来的是 第二层
 
@first('北京')
def fm():
    print('我们开始收听广播!')
 
fm()
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值