装饰器
为了增加功能而对函数或者类进行功能扩充的一种语法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| def decor(func): print('抱抱') func() print('举高高')
def love(): print('亲亲')
love = decor(love)
print(love)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| def decor(func): def inner(): print('抱抱') func() print('举高高')
return inner
def love(): print('亲亲') love = decor(love)
love()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def decor(func): def inner(): print('抱抱') func() print('举高高')
return inner
@decor def love(): print('亲亲')
love()
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| def decor(func): def inner(): print('抱抱') var = func() print('举高高') return var return inner
@decor def love(): print('亲亲') return '❤'
result = love() print(result)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| def decor(func): def inner(w1,w2): print('抱抱') func(w1,w2) print('举高高') return inner
@decor def love(who1,who2): print('{}亲亲{}'.format(who1,who2))
love('妈妈','女儿')
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| def decor(func): def inner(*p,**w): print('抱抱') func(*p,**w) print('举高高') return inner
@decor def love(*parent,**child): print(parent,'亲亲',child)
love('爸爸','妈妈',son = '儿子',girl = '女儿')
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| def outer(arg): def decor(func): def inner(): if arg == 'xiao': print('我给你将一个笑话') func() print('肚子疼了吧') elif arg == 'ku': print('告诉你一个不行的消息') func() print('没事,节哀顺变~') return inner return decor
@outer('xiao') def smile(): print('哈哈哈哈哈~')
@outer('ku') def cry(): print('呜呜呜呜~')
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Parent: def baobao(): print('抱抱') def jugaogao(): print('举高高')
def outer(cls): def decor(func): def inner(): cls.baobao() func() cls.jugaogao() return inner return decor
@outer(Parent) def love(): print('亲亲')
love()
|