Python 学习入门(38)—— @functools模块

2024-02-15 03:08

本文主要是介绍Python 学习入门(38)—— @functools模块,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.


functools 源码路径及内置函数:



利用@functools对函数运行时间,进行计时

代码示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.netimport time, functoolsdef timeit(func):@functools.wraps(func)def __do__(*args, **kwargs):start = time.time()result = func(*args, **kwargs)print("%s usedtime: %ss" % (func.__name__, time.time() - start))return resultreturn __do__@timeit
def print_str(num):sum = 0for i in range(num):sum += iprint sum@timeit
def main():print("print_str(100)")print_str(100)print("print_str(10000)")print_str(10000)print("print_str(1000000)")print_str(1000000)if __name__ == "__main__":  main()
运行结果:

print_str(100)
4950
print_str usedtime: 3.60012054443e-05s
print_str(10000)
49995000
print_str usedtime: 0.000550985336304s
print_str(1000000)
499999500000
print_str usedtime: 0.0614850521088s
main usedtime: 0.0623250007629s

说明:运行结果中的红色部分,都是运行计时的结果


示例2:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.netimport time, functoolsdef functools_wrapper(func):@functools.wraps(func)def wrapper(*args, **kwargs):print("call from functools_wrapper...")start = time.time()result = func(*args, **kwargs)print("%s usedtime: %ss" % (func.__name__, time.time() - start))
#         return func(*args, **kwargs)    return resultreturn wrapper@functools_wrapper
def functools_partial():print(int('10'))        # 10print(int('10', 2))     # 2int2 = functools.partial(int, base=2)print(int2('10'))       # 2print(int2('1010'))     # 10int2 = functools.partial(int, base=8)print(int2('10'))       # 8print(int2('1010'))     # 520@functools_wrapper
def functools_reduce():array = [1, 2, 3, 4, 5, 6]result = reduce((lambda x,y:x*y), array)print("result = %d" % result)           # 720result = functools.reduce((lambda x,y:x*y), array)print("result = %d" % result)            # 720def main():functools_partial()functools_reduce()if __name__ == "__main__":  main()
运行结果:

call from functools_wrapper...
10
2
2
10
8
520
functools_partial usedtime: 2.00271606445e-05s
call from functools_wrapper...
result = 720
result = 720
functools_reduce usedtime: 1.21593475342e-05s


参考推荐:

Python的functools模块

Python的functools


这篇关于Python 学习入门(38)—— @functools模块的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python中的魔术方法__new__详解

《Python中的魔术方法__new__详解》:本文主要介绍Python中的魔术方法__new__的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、核心意义与机制1.1 构造过程原理1.2 与 __init__ 对比二、核心功能解析2.1 核心能力2.2

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

Python 中的 with open文件操作的最佳实践

《Python中的withopen文件操作的最佳实践》在Python中,withopen()提供了一个简洁而安全的方式来处理文件操作,它不仅能确保文件在操作完成后自动关闭,还能处理文件操作中的异... 目录什么是 with open()?为什么使用 with open()?使用 with open() 进行

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求

Qt spdlog日志模块的使用详解

《Qtspdlog日志模块的使用详解》在Qt应用程序开发中,良好的日志系统至关重要,本文将介绍如何使用spdlog1.5.0创建满足以下要求的日志系统,感兴趣的朋友一起看看吧... 目录版本摘要例子logmanager.cpp文件main.cpp文件版本spdlog版本:1.5.0采用1.5.0版本主要

Python 迭代器和生成器概念及场景分析

《Python迭代器和生成器概念及场景分析》yield是Python中实现惰性计算和协程的核心工具,结合send()、throw()、close()等方法,能够构建高效、灵活的数据流和控制流模型,这... 目录迭代器的介绍自定义迭代器省略的迭代器生产器的介绍yield的普通用法yield的高级用法yidle

使用Python将JSON,XML和YAML数据写入Excel文件

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

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

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