Python中@装饰器的作用

2018-05-15  本文已影响34人  A丶英雄

转载请注明出处:https://www.jianshu.com/u/0d277af5103c

要了解python中@装饰器的作用,首先要记住这么几点:

def add(x, y):
... return x + y
def sub(x, y):
... return x - y
def apply(func, x, y): # 1
... return func(x, y) # 2
apply(add, 2, 1) # 3
3
apply(sub, 2, 1)
1
了解上述观点后,可以先不用@符号来写一个简单的装饰器
def decorate(func):

def decorate(func):

def inner(a, b):

    ret = func(a, b):

    return abs(ret)

return inner

def sub(a, b):

return a-b

sub(3, 4)

... -1

sub = decorate(sub)

sub(3, 4)

1

对于sub = decorate(sub)的理解。 最终会将inner的值传给sub ,此时执行sub(3, 4),其实是执行decorate中的inner,所以为1.

那么为了书写方便,将sub=decorate(sub)换为@decorate,并放在sub的定义面前,即:

@decorate

def sub(a, b):

return a-b

只是书写不同,结果相同。

希望可以帮助到大家!

上一篇 下一篇

猜你喜欢

热点阅读