函数的调用
定义
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()