由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。
def hello():
print ("hello world")
m = hello
m()
结果:hello world
要增强hello()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改hello()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
借助Python的@语法,把decorator置于函数的定义处:def log(func): def wrapper(*args, **kw): print("***start***") func(*args, **kw)
print("***end***") return wrapper
@log
def hello():
print ("hello world")
调用hello()
函数,不仅会运行 hello() 函数本身,还会在运行hello()函数前打印一行日志:
hello()
结果:
***start***
hello world
***end***
把@log
放到hello()
函数的定义处,相当于执行了语句:
hello = log(hello)