python 装饰器重要在哪

作者:Huangwei AI 时间:2023-12-30 12:13:29 

1.什么是装饰器?

要理解什么是装饰器,您首先需要熟悉Python处理函数的方式。从它的观点来看,函数和对象没有什么不同。它们有属性,可以重新分配:


def func():
print('hello from func')
func()
> hello from func
new_func = func
new_func()
> hello from func
print(new_func.__name__)
> func

此外,你还可以将它们作为参数传递给其他函数:


def func():
print('hello from func')
def call_func_twice(callback):
callback()
callback()
call_func_twice(func)
> hello from func
> hello from func

现在,我们介绍装饰器。装饰器(decorator)用于修改函数或类的行为。实现这一点的方法是定义一个返回另一个函数的函数(装饰器)。这听起来很复杂,但是通过这个例子你会理解所有的东西:


def logging_decorator(func):
def logging_wrapper(*args, **kwargs):
print(f'Before {func.__name__}')
func(*args, **kwargs)
print(f'After {func.__name__}')
return logging_wrapper

@logging_decorator
def sum(x, y):
print(x + y)

sum(2, 5)
> Before sum
> 7
> After sum

让我们一步一步来:

  1. 首先,我们在第1行定义logging_decorator函数。它只接受一个参数,也就是我们要修饰的函数。

  2. 在内部,我们定义了另一个函数:logging_wrapper。然后返回logging_wrapper,并使用它来代替原来的修饰函数。

  3. 在第7行,您可以看到如何将装饰器应用到sum函数。

  4. 在第11行,当我们调用sum时,它不仅仅调用sum。它将调用logging_wrapper,它将在调用sum之前和之后记录日志。

2.为什么需要装饰器

这很简单:可读性。Python因其清晰简洁的语法而备受赞誉,装饰器也不例外。如果有任何行为是多个函数共有的,那么您可能需要制作一个装饰器。下面是一些可能会派上用场的例子:

  • 在运行时检查实参类型

  • 基准函数调用

  • 缓存功能的结果

  • 计数函数调用

  • 检查元数据(权限、角色等)

  • 元编程

和更多…

现在我们将列出一些代码示例。

3.例子

带有返回值的装饰器

假设我们想知道每个函数调用需要多长时间。而且,函数大多数时候都会返回一些东西,所以装饰器也必须处理它:


def timer_decorator(func):
def timer_wrapper(*args, **kwargs):
import datetime  
before = datetime.datetime.now()  
result = func(*args,**kwargs)
after = datetime.datetime.now()  
print "Elapsed Time = {0}".format(after-before)
return result

@timer_decorator
def sum(x, y):
print(x + y)
return x + y

sum(2, 5)
> 7
> Elapsed Time = some time

可以看到,我们将返回值存储在第5行的result中。但在返回之前,我们必须完成对函数的计时。这是一个没有装饰者就不可能实现的行为例子。

带有参数的装饰器

有时候,我们想要一个接受值的装饰器(比如Flask中的@app.route('/login'):


def permission_decorator(permission):
def _permission_decorator(func):
def permission_wrapper(*args, **kwargs):
if someUserApi.hasPermission(permission):
result = func(*args, **kwargs)
return result
return None
return permission wrapper
return _permission_decorator

@permission_decorator('admin')
def delete_user(user):
someUserApi.deleteUser(user)

为了实现这一点,我们定义了一个额外的函数,它接受一个参数并返回一个装饰器。

带有类的装饰器

使用类代替函数来修饰是可能的。唯一的区别是语法,所以请使用您更熟悉的语法。下面是使用类重写的日志装饰器:


class Logging:

def __init__(self, function):
self.function = function

def __call__(self, *args, **kwargs):
print(f'Before {self.function.__name__}')
self.function(*args, **kwargs)
print(f'After {self.function.__name__}')

@Logging
def sum(x, y):
print(x + y)

sum(5, 2)
> Before sum
> 7
> After sum

这样做的好处是,您不必处理嵌套函数。你所需要做的就是定义一个类并覆盖__call__方法。

装饰类

有时,您可能想要修饰类中的每个方法。你可以这样写


class MyClass:
@decorator
def func1(self):
pass
@decorator
def func2(self):
pass

但如果你有很多方法,这可能会失控。值得庆幸的是,有一种方法可以一次性装饰整个班级:


def logging_decorator(func):
def logging_wrapper(*args, **kwargs):
print(f'Before {func.__name__}')
result = func(*args, **kwargs)
print(f'After {func.__name__}')
return result
return logging_wrapper

def log_all_class_methods(cls):
class NewCls(object):
def __init__(self, *args, **kwargs):
self.original = cls(*args, **kwargs)

def __getattribute__(self, s):
try:
x = super(NewCls,self).__getattribute__(s)
except AttributeError:
pass
else:
return x
x = self.original.__getattribute__(s)
if type(x) == type(self.__init__):
return logging_decorator(x)  
else:
return x
return NewCls

@log_all_class_methods
class SomeMethods:
def func1(self):
print('func1')

def func2(self):
print('func2')

methods = SomeMethods()
methods.func1()
> Before func1
> func1
> After func1

现在,不要惊慌。这看起来很复杂,但逻辑是一样的:

  • 首先,我们让logging_decorator保持原样。它将应用于类的所有方法。

  • 然后我们定义一个新的装饰器:log_all_class_methods。它类似于普通的装饰器,但却返回一个类。

  • NewCls有一个自定义的__getattribute__。对于对原始类的所有调用,它将使用logging_decorator装饰函数。

内置的修饰符

您不仅可以定义自己的decorator,而且在标准库中也提供了一些decorator。我将列出与我一起工作最多的三个人:

@property -一个内置插件的装饰器,它允许你为类属性定义getter和setter。

@lru_cache - functools模块的装饰器。它记忆函数参数和返回值,这对于纯函数(如阶乘)很方便。

@abstractmethod——abc模块的装饰器。指示该方法是抽象的,且缺少实现细节。

来源:http://developer.51cto.com/art/202102/645688.htm

标签:python,装饰器
0
投稿

猜你喜欢

  • 通过底层源码理解YOLOv5的Backbone

    2023-07-15 20:37:01
  • Vue2.0在IE11版本浏览器中的兼容性问题

    2024-04-29 13:08:55
  • Mysql 执行一条语句的整个过程详细

    2024-01-19 08:53:08
  • python中hasattr()、getattr()、setattr()函数的使用

    2022-12-11 20:14:27
  • javascript实现延时显示提示框效果

    2024-04-25 13:10:42
  • Python3.9.1中使用split()的处理方法(推荐)

    2022-04-17 23:16:12
  • 开心网上input输入框研究

    2009-03-06 12:52:00
  • Bootstrap实现提示框和弹出框效果

    2023-07-02 05:25:33
  • Go语言题解LeetCode724寻找数组的中心下标

    2023-07-09 03:26:01
  • javascript中正则表达式语法详解

    2024-05-02 16:17:04
  • Python使用pandas对数据进行差分运算的方法

    2021-09-28 06:56:07
  • Sql 批量查看字符所在的表及字段

    2024-01-15 02:53:36
  • 安装多个版本的TensorFlow的方法步骤

    2022-12-10 00:13:02
  • vue实现某元素吸顶或固定位置显示(监听滚动事件)

    2024-05-09 15:15:10
  • Python把图片转化为pdf代码实例

    2021-04-05 19:06:36
  • python框架Django实战商城项目之工程搭建过程图文详解

    2022-12-16 16:25:57
  • Python 获取div标签中的文字实例

    2023-03-27 01:53:53
  • mysql调优的几种方式小结

    2024-01-25 22:24:41
  • Go语言题解LeetCode268丢失的数字示例详解

    2024-05-02 16:24:29
  • python实现博客文章爬虫示例

    2022-06-30 08:20:40
  • asp之家 网络编程 m.aspxhome.com