装饰器(Decorators)

首先说一下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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值