024、装饰器
本文最后更新于 67 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com

装饰器

基础用法

以函数作为参数,并且返回一个新函数的函数是一个装饰器:

def dec(f):
    print(f'I am decorating function {f.__name__}')
    return f
dec(len)
I am decorating function len

装饰器可以在函数定义时用@调用:

@dec
def add(x, y):
    return x + y
I am decorating function add

调用add相当于调用 dec(add)

再如,定义两个装饰器函数,一个将原来的函数值加一,另一个乘二:

def plus_one(f):
    def new_func(x):
        return f(x) + 1
    return new_func

def times_two(f):
    def new_func(x):
        return f(x) * 2
    return new_func

定义函数,先乘二再加一:

@plus_one
@times_two
def foo(x):
    return x
foo(13)
27

调用foo(x)相当于调用 plus_one(times_two(foo))(x)

装饰器工厂

生成装饰器的函数被叫做装饰器工厂。将plus_one一般化为一个名为plus_n的装饰器工厂:

def plus_n(n):
    def plus_dec(f):
        def new_func(x):
            return f(x) + n
        return new_func
    return plus_dec

可以将plus_one替换为plus_n(1)

@plus_n(1)
@times_two
def foo(x):
    return x
foo(13)
27
谨此笔记,记录过往。凭君阅览,如能收益,莫大奢望。
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇