云学编程的23天—【微软官方python入门教程 P40笔记】2021-11-21 P42-P43装饰器Decorators以及实操

本文深入探讨了Python中的装饰器,解释了它们作为代码修饰符的角色,如何添加额外功能,以及在实际项目中的应用场景,如日志记录和认证。通过示例展示了如何创建和使用装饰器,以及它们如何改变函数执行流程。

Programming components

 

Object: Nouns ; Data constructs ; They're the things that we're going to operate upon.

Functions/Methods: Verbs ; Actions ; They're all the different things that we're going to be able to do.

eg: My OS you might consider that an object. getenv that's going to be our verb.

Decorators : Adjectives;  Add additional functionality to code; Common in frameworks

Using a decorator

#Snippet from Flask
#register https://myserver/api/products
@route('api/products') #route registration
def get_products:
    #code to list from database
    pass

使用装饰器@route告诉Flask,当某人访问api/products,这里的代码就是我要调用的。

这就是幕后的样子:

Creating a decorator

def logger(func):
     def wrapper():
          print('Logging execution')#我的code
          func() #你的code
          print('Done logging')#我的code
     return wrapper
@logger。        #如果某人用我们的装饰器,你(python)就调用制定函数wrapper()
def sample():
     print('-- Inside sample function ')
sample()
 

Logging execution
-- Inside sample function #执行func()
Done logging 

#利用注解的形式实现了一个AOP功能 ——弹幕(虽然看不懂觉得很厉害的样子)

应用场景:

If I need to log execution which is what I'm trying to demo here, or maybe there's something where I need to do some level of authentication身份认证, and I need to make sure that the users log on, then I might go ahead and create a Decorator. 

P43实操 

def logger(func):
     def wrapper():
          print('Logging execution')#我的code
          func() #你的code
          print('Done logging')#我的code
     return wrapper
@logger      #如果某人用我们的装饰器,你(python)就调用制定函数wrapper()
def sample():
     print('-- Inside sample function ')
sample()

 def wrapper():
          print('Logging execution')
          func()
          print('Done logging')

⬆️这段代码是装饰器运行时执行的代码

@logger 

⬆️设置名为logger的装饰器

def sample():

⬆️这就是func函数,先print Log...再运行sample函数(这里会运行print('-- Inside sample function ')),最后print Done...

⬇️运行结果: 

Logging execution
-- Inside sample function 
Done logging

If you ever decided that this functionality might work in something that you're building that is how you can go in and create a simple docorator. 如果你正在构建的是你要用的功能,不想改变原定义,就可以创建一个装饰器。  

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值