跟着我们一起学 Python 30天课程-第13天-Decorators
今天,我探讨了一个有趣的主题,装饰器。在尝试使用诸如@classmethod
和的Python进行面向对象的编程时,我确实应用了几个装饰器@staticmethod
,但是,那时我没有详细介绍它们。
装饰器是一种编程模式。装饰器只是伪装的功能。
使用装饰器,可以向功能添加更多功能或对其进行超级充电。
我将尝试以自己清楚的术语来解释它们如何在后台运行以及它们为何有用。
许多很棒的Python库大量使用了装饰器,使它们看起来像魔术一样。但是,要了解装饰器,需要了解一些概念。
Functions as first-class citizens
函数是Python中的一等公民。从本质上讲,这意味着可以像其他数据类型一样将函数分配给变量,并且可以像其他值一样将它们作为参数传递给函数。在JavaScript世界中,函数的行为也相似,因此我的思维模型中已经有了这个概念。
def multiplier(num1, num2):
return num1 * num2
some_variable = multiplier # (a reference to the function is created)
del multiplier # (deletes the function)
print(some_variable(2,4)) # 8 (still able to call the function!)
这种将函数作为值传递的能力对于在Python中创建装饰器至关重要。
高阶函数 Higher-Order Functions
在以下情况下,一个函数称为高阶函数:
- 它接受另一个函数作为参数(参数)
- 它返回另一个函数
- 都
def logger(func, args): # higher order function
print(f'The result of the passed function is {func(*args)}')
def sum(num1, num2):
return num1 + num2
logger(sum, (1, 5))
def random(): # Higher order function
def special():
print('I am something special')
return special
random_value = random()
random_value() # I am something special
# One line way
random()() # I am something special
Custom Decorators
现在使用上述原理,这是自定义装饰器的外观
def starmaker(func):
'''
A decorator function which accepts a function
and then wraps some goodness into it and
returns it back!
'''
def wrapper():
func()
print('You are a star now!')
print('*********')
return wrapper
@starmaker
def layman():
print('I am just a layman')
layman()
starmaker装饰器功能赋予了外行功能以超能力。基本上,它为该函数添加了一个包装器。现在,可以在任何功能之上添加此装饰器@starmaker,该功能将成为明星!确实很酷。
Python解释器可识别@decoratorname
并将其实时转换为函数并进行处理。上面的代码与下面的代码块完全相似,没有使用@decorator
语法
def starmaker(func):
'''
A decorator function which accepts a function
and then wraps some goodness into it and
returns it back!
'''
def wrapper():
func()
print('You are a star now!')
print('*********')
return wrapper
def layman():
print('I am just a layman')
starmaker(layman)() # This is the underlying decorator magic!
当我遇到装饰者时,我最初很困惑。但是,在揭开他们的基本原理神秘面纱之后,它成为了第二天性,我得以将其添加到我的心理模型中。
如果将其与JavaScript Universe进行比较,则JavaScript不会将装饰器作为语言的一部分。但是,作为JavaScript的超集的TypeScript具有这种装饰器的概念。像Angular,NestJs这样的框架在很大程度上依赖装饰器。
装饰器函数还可以接受参数,并且可以根据传递的参数进行自定义。
def emojifier(func):
def wrapper(emoji):
# kwags are keyword arguments
print(emoji)
func()
return wrapper
@emojifier
def random():
pass
random('😀') # 😀
Why decorators are useful?
装饰器是一种重要的编程模式,如果使用得当,可以带来很多好处。它使代码具有很高的可重用性,并将添加的功能绑定到函数,从而使代码保持DRY。
# Create an @authenticated decorator that only allows
# the function to run is user1 has 'valid' set to True:
test_user = {
'name': 'Jackson',
'valid': True
}
another_user = {
'name': 'Nathan',
'valid': False
}
def authenticated(fn):
def wrapper(*args, **kwargs):
if args[0]['valid']:
fn(args)
return wrapper
@authenticated
def message_friends(user):
print('message has been sent')
message_friends(test_user) # message has been sent
message_friends(another_user) # (Does nothing)
上面认证的装饰器函数仅根据指定的条件调用message_friends函数。这提供了很大的灵活性,并根据用户身份验证的状态执行条件操作。
参考文章,以了解有关Python装饰器的更多信息:
- https://www.programiz.com/python-programming/decorator
- https://realpython.com/primer-on-python-decorators/
今天就这些。明天我将探讨有关Python中错误处理技术的所有内容。另一个重要的话题。
跟着我们一起学 Python 30天课程目录:
- 跟着我们一起学 Python 30天课程-第30天-免费Python资源
- 跟着我们一起学 Python 30天课程-第29天-自动化测试
- 跟着我们一起学 Python 30天课程-第28天-ML和数据科学II
- 跟着我们一起学 Python 30天课程-第27天-ML和数据科学I
- 跟着我们一起学 Python 30天课程-第26天-机器学习基础
- 跟着我们一起学 Python 30天课程-第25天-Web 开发进阶
- 跟着我们一起学 Python 30天课程-第24天-Web开发基础
- 跟着我们一起学 Python 30天课程-第23天-网页爬虫
- 跟着我们一起学 Python 30天课程-第22天-脚本额外功能Scripting Extras
- 跟着我们一起学 Python 30天课程-第21天-脚本编写基础
- 跟着我们一起学 Python 30天课程-第20天-调试和测试
- 跟着我们一起学 Python 30天课程-第19天-正则表达式
- 跟着我们一起学 Python 30天课程-第18天-文件I / O
- 跟着我们一起学 Python 30天课程-第17天-外部模块External Modules
- 跟着我们一起学 Python 30天课程-第16天-模块基础Module Basics
- 跟着我们一起学 Python 30天课程-第15天-生成器Generators
- 跟着我们一起学 Python 30天课程-第14天-错误处理Error Handling
- 跟着我们一起学 Python 30天课程-第13天-Decorators
- 跟着我们一起学 Python 30天课程-第12天-Lambda Expressions & Comprehensions
- 跟着我们一起学 Python 30天课程-第11天-函数编程Functional Programming基础
- 跟着我们一起学 Python 30天课程-第10天-OOP Missing Pieces
- 跟着我们一起学 Python 30天课程-第9天-OOP Pillars
- 跟着我们一起学 Python 30天课程-第8天-OOP基础知识
- 跟着我们一起学 Python 30天课程-第7天-开发环境搭建(Developer Environment)
- 跟着我们一起学 Python 30天课程-第6天-循环II和函数(Loops II & Functions)
- 跟着我们一起学 Python 30天课程-第5天-条件和循环I(Conditions & Loops I)
- 跟着我们一起学 Python 30天课程-第4天-数据类型III(Data Types III)
- 跟着我们一起学 Python 30天课程-第3天-数据类型II(Data Types II)
- 跟着我们一起学 Python 30天课程-第2天-数据类型I(Data Types I)
- 跟着我们一起学 Python 30天课程-第1天-简介
1. 本站资源转自互联网,源码资源分享仅供交流学习,下载后切勿用于商业用途,否则开发者追究责任与本站无关!
2. 本站使用「署名 4.0 国际」创作协议,可自由转载、引用,但需署名原版权作者且注明文章出处
3. 未登录无法下载,登录使用金币下载所有资源。
IT小站 » 跟着我们一起学 Python 30天课程-第13天-Decorators
常见问题FAQ
- 没有金币/金币不足 怎么办?
- 本站已开通每日签到送金币,每日签到赠送五枚金币,金币可累积。
- 所有资源普通会员都能下载吗?
- 本站所有资源普通会员都可以下载,需要消耗金币下载的白金会员资源,通过每日签到,即可获取免费金币,金币可累积使用。