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. 如果你正在构建的是你要用的功能,不想改变原定义,就可以创建一个装饰器。
本文深入探讨了Python中的装饰器,解释了它们作为代码修饰符的角色,如何添加额外功能,以及在实际项目中的应用场景,如日志记录和认证。通过示例展示了如何创建和使用装饰器,以及它们如何改变函数执行流程。

被折叠的 条评论
为什么被折叠?



