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将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用

Spring Boot项目部署命令java -jar的各种参数及作用详解

《SpringBoot项目部署命令java-jar的各种参数及作用详解》:本文主要介绍SpringBoot项目部署命令java-jar的各种参数及作用的相关资料,包括设置内存大小、垃圾回收... 目录前言一、基础命令结构二、常见的 Java 命令参数1. 设置内存大小2. 配置垃圾回收器3. 配置线程栈大小

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件

解决SpringBoot启动报错:Failed to load property source from location 'classpath:/application.yml'

《解决SpringBoot启动报错:Failedtoloadpropertysourcefromlocationclasspath:/application.yml问题》这篇文章主要介绍... 目录在启动SpringBoot项目时报如下错误原因可能是1.yml中语法错误2.yml文件格式是GBK总结在启动S

Python基础语法中defaultdict的使用小结

《Python基础语法中defaultdict的使用小结》Python的defaultdict是collections模块中提供的一种特殊的字典类型,它与普通的字典(dict)有着相似的功能,本文主要... 目录示例1示例2python的defaultdict是collections模块中提供的一种特殊的字

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

java实现延迟/超时/定时问题

《java实现延迟/超时/定时问题》:本文主要介绍java实现延迟/超时/定时问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java实现延迟/超时/定时java 每间隔5秒执行一次,一共执行5次然后结束scheduleAtFixedRate 和 schedu