龙空技术网

彻底学会Python 中的“装饰器

自由坦荡的湖泊AI 167

前言:

而今大家对“python修饰”可能比较注重,朋友们都想要分析一些“python修饰”的相关内容。那么小编也在网上搜集了一些有关“python修饰””的相关内容,希望咱们能喜欢,小伙伴们快快来学习一下吧!

在 python 中,装饰器是一种特殊类型的函数,用于修改或扩展其他函数或方法的行为。装饰器通常在函数或方法中应用或使用,以向它们添加其他功能,而无需直接修改源代码。

什么是 Python 中的装饰器?

定义:装饰器函数是一个高阶函数,它接受另一个函数作为参数并返回一个新函数。此新函数通常会扩展或修改原始函数的行为。修饰器函数通常以特殊字符“@”为前缀,并始终放置在要修饰的函数上方。

以下代码部分显示了装饰器的一些示例,以及如何使用它们来扩展更改原始源代码的函数。

示例 01

# defining normal functiondef test():  print("The addition of two odd numbers 3 and 7")  print(3 + 7)  print("is always an even number")test()
Output:The addition of two odd numbers 3 and 710is always an even number
# defining a decorator functiondef sum_decorator(func):  def inner_deco():    print("The addition of two odd numbers 3 and 7")    func()    print("is always an even number")  return inner_deco
# funtion without using decoratordef odd_add():  print(3+7)odd_add()
Output:10
# using a decorator to extend the functionality of a normal odd addition function@sum_decoratordef odd_add():  print(3+7)odd_add()
Output:The addition of two odd numbers 3 and 710is always an even numbe
示例 02
#defining new decoratordef deco(func):  def inner_deco():    print("The addition odd numbers upto 10 is")    func()  return inner_deco#using decorator on the function extending its functionality@decodef odd_add():  sum = 0  for i in range(10):    if i%2 != 0:      sum += i  print(sum)#calling the decorated function  odd_add()
Output:The addition odd numbers upto 10 is25
为什么需要 OOP 中的装饰器?它在编码方面有什么好处?01 — 代码可重用性

装饰器通过允许编码人员将通用功能或 bahavior 应用于多个函数或方法来促进代码的可重用性。当我们有多个具有相似行为的类时,这种做法在 OOP 中编写代码时很有用。

02 — 关注点分离

装饰器帮助我们编码人员分离代码的不同关注点或方面。例如,可以有用于登录、身份验证等的装饰器。这种为每个不同的任务使用不同的装饰器的分离使代码库更简洁且易于维护,尤其是在协作环境中工作时。

03 — 开放式或封闭式原理

装饰器遵循面向对象编程的“开放/关闭原则”,该原则指出类或函数应该打开以进行扩展,但关闭以进行修改。在这种情况下,可以使用装饰器来扩展函数或方法的行为,而无需更改其源代码。

04 — 易于维护

装饰器使管理和维护代码变得更加容易,因为通过装饰器,始终可以在一个地方更新函数或方法的行为,而不是在整个代码库中进行更改。

05 — 提倡单一责任原则

装饰器可以通过允许我们将其他功能模块化到我们的函数或方法,来帮助确保每个函数或方法都具有单一的职责。

06 — 可读性

装饰器可以通过将函数或方法的核心功能与其辅助功能分开来增强代码的可读性。

标签: #python修饰