首先说一下python中的函数的特性:
一切皆对象;
可以在函数中定义函数,也就是说我们可以创建嵌套函数;
从函数中返回函数;
将函数作为参数传给另一个函数;
而装饰器:简单的说他们是修改其他函数的功能的函数。他们有助于让我们的代码更简短,也更Pythonic(Python范儿)。他们封装一个函数,用这样或者那样的方式来修改它的行为。
下面是函数特性的例子和一个简单的装饰器:
#一切皆对象
def hi(name='yasoob'):
return 'hi' + name
print(hi())
#我们可以将一个函数赋值给一个变量,这里并没有使用小括号,因为我们并不是在调用hi函数,而是将它放到greet变量里头
greet = hi
print(greet())
#如果我们删掉旧的hi函数,旧的函数就不能用了,而新赋值的可以
del hi
# print(hi())
print(greet())
#在函数中定义函数,函数中的函数在外面是不能访问的
def hi(name="yasoob"):
print("now you are inside the hi() function")
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
print(greet())
print(welcome())
print("now you are back in the hi() function")
hi()
# greet()
#从函数中返回函数
def hii(name="yasoob"):
def greet():
return "now you are in the greet() function"
def welcome():
return "now you are in the welcome() function"
if name == "yasoob":
return greet
else:
return welcome
a = hii()
print(a())
#将函数作为参数传给另一个函数
def hello():
return "hello world"
def dosomething(func):
print("I am doing some boring work")
print(func())
dosomething(hello)
#第一个装饰器(它们封装一个函数,并且用这样或者那样的方式来修改它的行为)
#应用场景:授权、日志
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
print("I am the function which needs some decoration to remove my foul smell")
a_function_requiring_decoration()
print(a_function_requiring_decoration.__name__)
运行结果:
D:\python3.6.1\python.exe F:/python_Advanced/decorators.py
hiyasoob
hiyasoob
hiyasoob
now you are inside the hi() function
now you are in the greet() function
now you are in the welcome() function
now you are back in the hi() function
now you are in the greet() function
I am doing some boring work
hello world
I am doing some boring work before executing a_func()
I am the function which needs some decoration to remove my foul smell
I am doing some boring work after executing a_func()
a_function_requiring_decoration
Process finished with exit code 0