Python的装饰器和Java的注解是一回事吗?

2024-02-05 13:18
文章标签 java python 注解 装饰 回事

本文主要是介绍Python的装饰器和Java的注解是一回事吗?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文为我在阅读Python’s decorators vs Java’s annotations, same thing?的笔记。

Flask 的路由看起来和 Spring 的机制非常像,比如用 Flask 定义的一个路由:将 Http 请求 GET: /hello 路由到 say_hello() 函数。

app = Flask(__name__)@app.route('/hello', methods=['GET'])
def say_hello():return 'hello'

Spring 用注解定义了路由,看起来跟 Flask 类似:


@RequestMapping(value = "/hello", method = GET)
class HelloController{@ResponseBodypublic String getHelloMessage() {return "hello";}
}

但实际上,Python 的装饰器 (decorator) 和 Java 的注解(annotation) 是完全不同的概念。Python 的装饰器本质上是返回另一个函数的函数用于装饰函数的时候,作为语法糖,实际上是函数的调用

下面我来详细解释一下这句加粗的这句话。我们定义 hello() 函数,返回一个字符串 hello:

def hello():return 'hello'if __name__ == '__main__':print(hello())

假如我们想将字符串变为 html 的标签 heading 1,可以定义一个函数提供这个转换:

def hello():return 'hello'def as_h1(message):return f'<h1>{message}</h1>'if __name__ == '__main__':print(as_h1(hello()))

如果使用装饰器实现相同的功能,只需要将 @as_h1 对 hello() 函数进行装饰:

def as_h1(func):def wrapper():result = func()return f'<h1>{result}</h1>'return wrapper@as_h1
def hello():return 'hello'if __name__ == '__main__':print(hello())

@as_h1 装饰器用于装饰 hello() 函数,本质是调用 as_h1() 函数。作为装饰器的函数要点:

  • 外函数返回内函数 : as_h1() 函数的返回值是内函数 wrapper (函数的 return wrapper 语句)
  • 内函数改变从外函数传入函数的行为:func 是传入参数,通过外函数 as_h1 传给 内函数 wrapper,在 wrapper 函数中被改变(func 函数被改变了)

之前写过一篇博文:理解和使用Python装饰器 比较详细的说明了装饰器的机制。

函数大多数是带参数的,所以一个实用的装饰器必须能处理含有参数的函数。下面的代码定义能处理带参数的装饰器,演示了装饰器的典型写法:

import time
cached_items = {}def cached(func):def wrapper(*args, **kwargs):global cached_itemif func.__name__ not in cached_items:cached_items[func.__name__] = func(*args, **kwargs)return cached_items[func.__name__]return wrapper

cached 装饰器的作用是对某个函数提供缓存机制,对某个函数比较耗时的函数,缓存可以提升效率。下面的代码演示了将 cached 装饰器作用于 intensive_task() 函数,第一次调用耗时 1 秒,第二次调用从缓存中获取,时间为 0:

@cached
def intensive_task():time.sleep(1.0)return 10start_time = time.time()
intensive_task()
print("INFO: %.8f seconds first execution" % (time.time() - start_time))start_time = time.time()
intensive_task()
print("INFO: %.8f seconds second execution" % (time.time() - start_time))

在我的 PC 上运行的结果如下:

python decorator_test2.py
INFO: 1.00221372 seconds first execution
INFO: 0.00000000 seconds second execution

而在 Java 中,注解其实就是一种特殊的注释,相当于对类、方法等贴一个标签,不会改变代码的行为。但为什么本文开头的代码中,@ReqeustMapping 注解实现了 Flask 相同的路由机制呢?其实是因为 Spring 框架发现某个方法被注解了,提供相应的功能实现而已。

比如说,定义一个 @Cached 注解,并且用在 intensiveTask() 方法上,此时与没有注解的代码,行为没有任何不同。

public class Main {@Retention(RetentionPolicy.RUNTIME)@interface Cached { } // Nothing inside our annotationstatic class SomeObject {@Cachedpublic String intensiveTask() throws InterruptedException {Thread.sleep(1000);return "expensive task result";}}public static void main(String[] args) throws Exception {long time = System.currentTimeMillis();final SomeObject expensiveTaskObject = new SomeObject();someObject.intensiveTask();System.out.println("First execution:" + (System.currentTimeMillis() - time));time = System.currentTimeMillis();someObject.intensiveTask();System.out.println("Second execution:" + (System.currentTimeMillis() - time));}
}

如果需要达到与 Python 代码相同的缓存效果,需要编写代码,将 intensiveTask() 方法加到缓存中:

static class SomeObjectExecutor {Map<String, String> cache = new HashMap<>();public String execute(SomeObject task) throws Exception {final Method intensiveTaskMethod = task.getClass().getDeclaredMethod("intensiveTask");if (intensiveTaskMethod.isAnnotationPresent(Cached.class)) {String className = task.getClass().getName();if (!cache.containsKey(className)) {cache.put(className, task.intensiveTask());}return cache.get(className);}return task.intensiveTask();}
}

然后在两次调用调用 intensiveTask() 方法的时候,通过执行 SomeObjectExecutor 类的 execute() 方法进行判断,如果缓存中已经有了 intensiveTask() 方法,则直接返回缓存中的方法,从而节省时间:

public static void main(String[] args) throws Exception {final SomeObjectExecutor someObjectExecutor = new SomeObjectExecutor();long time = System.currentTimeMillis();final SomeObject expensiveTaskObject = new SomeObject();someObjectExecutor.execute(expensiveTaskObject);System.out.println("First execution:" + (System.currentTimeMillis() - time));time = System.currentTimeMillis();someObjectExecutor.execute(expensiveTaskObject);System.out.println("Second execution:" + (System.currentTimeMillis() - time));
}

总结起来:

Java 的注解本身什么都不做,而 Python 的装饰器是函数,会改变被装饰函数的行为;
如果想改变 Java 被注解方法的行为,需要另外的代码判断某个方法是否被某个注解(名词)注解(动词),对被注解的方法提供不同的实现。

这篇关于Python的装饰器和Java的注解是一回事吗?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/681032

相关文章

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Python pandas库自学超详细教程

《Pythonpandas库自学超详细教程》文章介绍了Pandas库的基本功能、安装方法及核心操作,涵盖数据导入(CSV/Excel等)、数据结构(Series、DataFrame)、数据清洗、转换... 目录一、什么是Pandas库(1)、Pandas 应用(2)、Pandas 功能(3)、数据结构二、安

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

Python安装Pandas库的两种方法

《Python安装Pandas库的两种方法》本文介绍了三种安装PythonPandas库的方法,通过cmd命令行安装并解决版本冲突,手动下载whl文件安装,更换国内镜像源加速下载,最后建议用pipli... 目录方法一:cmd命令行执行pip install pandas方法二:找到pandas下载库,然后

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick