python工具的功能介绍

One of the biggest power which Python demonstrates is providing tools for writing reusable code. In this lesson, we will learn about Python functools module, which makes writing reusable code easy and very much maintainable.

Python演示的最大功能之一就是提供用于编写​​可重用代码的工具。 在本课程中,我们将学习Python functools模块,该模块使编写可重用的代码变得容易且非常可维护。

Python functools模块 (Python functools module)

Python functools module provides us various tools which allows and encourages us to write reusable code. Some of them are:

Python functools模块为我们提供了各种工具,这些工具允许并鼓励我们编写可重用的代码。 他们之中有一些是:

  • Partial functions部分功能
  • Updating Partial wrappers更新部分包装器
  • Total ordering总订购

Let’s start our post with a short and informative discussion on partial functions.

让我们以关于局部函数的简短而丰富的讨论开始我们的文章。

什么是部分功能? (What are partial functions?)

Python functools partial functions are used to:

Python functools局部函数用于:

  • Replicate existing functions with some arguments already passed in.使用已传入的一些参数复制现有函数。
  • Creating new version of the function in a well-documented manner.以有据可查的方式创建功能的新版本。

使用functools的部分功能 (partial functions using functools)

The points we stated above can be well understood with some examples. Let’s study them now.

我们上面列举的几点可以通过一些例子很好地理解。 让我们现在研究它们。

Suppose you have a function called multiplier which just multiplies two numbers. Its definition looks like:

假设您有一个名为multiplier的函数,该函数仅将两个数字相乘。 其定义如下:

def multiplier(x, y):return x * y

Now, what if we want to make some dedicated functions to double or triple a number? We will have to define new functions as:

现在,如果我们想做一些专用的功能来将数字加倍或三倍呢? 我们将必须定义新功能为:

def multiplier(x, y):return x * ydef doubleIt(x):return multiplier(x, 2)def tripleIt(x):return multiplier(x, 3)

Well, these were easy but what happens when we need 1000 such functions? Here, we can use partial functions:

好吧,这些很容易,但是当我们需要1000个这样的功能时会发生什么呢? 在这里,我们可以使用部分函数:

from functools import partialdef multiplier(x, y):return x * ydouble = partial(multiplier, y=2)
triple = partial(multiplier, y=3)print('Double of 2 is {}'.format(double(5)))

Well, that was much shorter, isn’t it? Output of the example remains unaffected as:

We can even make multiple partials in a loop:

好吧,那要短得多,不是吗? 该示例的输出不受影响,因为:

我们甚至可以在循环中制作多个局部:

from functools import partialdef multiplier(x, y):return x * ymultiplier_partials = []
for i in range (1, 11):function = partial(multiplier, i)multiplier_partials.append(function)print('Product of 1 and 2 is {}'.format(multiplier_partials[0](2)))
print('Product of 3 and 2 is {}'.format(multiplier_partials[2](2)))
print('Product of 9 and 2 is {}'.format(multiplier_partials[8](2)))

This time, we collected more functions in a list and called them. Output will be:

这次,我们在列表中收集了更多函数并将其称为。 输出将是:

部分功能是自我记录的 (partial functions are self-documented)

Even though partial functions can be treated as completely independent functions, they themselves never lose the memory of the function which powers them.

即使可以将部分功能视为完全独立的功能,但它们本身也永远不会失去为其提供动力的功能的记忆。

This can be proved from the doc meta-data they hold:

这可以从他们拥有的文档元数据中得到证明:

from functools import partialdef multiplier(x, y):return x * ydouble = partial(multiplier, y=2)
triple = partial(multiplier, y=3)print('Function powering double is {}'.format(double.func))
print('Default keywords for double is {}'.format(double.keywords))

Output will be:

First call gives the function name with its memory address.

输出将是:

首次调用将给出函数名称及其内存地址。

在functools中测试部分功能 (Testing partial functions in functools)

It is simple to test a partial function. We can even test its documentation. Let’s see how it is done:

测试部分功能很简单。 我们甚至可以测试其文档。 让我们看看它是如何完成的:

from functools import partialdef multiplier(x, y):return x * ydouble = partial(multiplier, y=2)
triple = partial(multiplier, y=3)assert double.func == multiplier
assert double.keywords == {'y': 2}

When you run this script, you won’t see any output as Assertions only give an error output when they fail. If they pass, they silently continue the execution of the code.

运行此脚本时,您将看不到任何输出,因为断言仅在失败时给出错误输出。 如果通过,则它们将静默继续执行代码。

使用functool.update_wrapper()更新部分函数元数据 (Update partial function metadata with functool.update_wrapper())

With functools module, we can update metadata of a function with wrappers. Let us look at example code snippet to clarify how this is done:

借助functools模块,我们可以使用包装器更新函数的元数据。 让我们看一下示例代码片段,以阐明如何完成此操作:

import functoolsdef multiplier(x, y):"""Multiplier doc string."""return x * ydef show_details(name, function):"""Details callable object."""print('Name: {}'.format(name))print('\tObject: {}'.format(function))try:print('\t__name__: {}'.format(function.__name__))except AttributeError:print('\t__name__: {}'.format('__no name__'))print('\t__doc__ {}'.format(repr(function.__doc__)))returndouble = functools.partial(multiplier, y=2)show_details('raw wrapper', double)print('Updating wrapper:')
print('\tassign: {}'.format(functools.WRAPPER_ASSIGNMENTS))
print('\tupdate: {}'.format(functools.WRAPPER_UPDATES))functools.update_wrapper(double, multiplier)
show_details('updated wrapper', double)

Output of this script will be:

Before update wrapper, the partial function didn’t have any data about its name and proper doc string but update_wrapper() function changed that.

该脚本的输出为:

在更新包装器之前,部分函数没有有关其名称和适当的文档字符串的任何数据,但是update_wrapper()函数对此进行了更改。

使用functool进行总订购 (Total ordering with functool)

functools module also provide a way to provide automatic comparison functions. There are 2 conditions which needs to be met to accomplish the results:

functools模块还提供了一种提供自动比较功能的方法。 要实现结果,需要满足两个条件:

  1. Definition of at least one comparison function is a must like le, lt, gt or ge.必须至少定义一个比较函数,例如leltgtge
  2. Definition of eq function is mandatory.eq函数的定义是强制性的。

So, this is what we will do:

因此,这是我们将要做的:

from functools import total_ordering@total_ordering
class Number:def __init__(self, value):self.value = valuedef __lt__(self, other):return self.value < other.valuedef __eq__(self, other):return self.value == other.valueprint(Number(1) < Number(2))
print(Number(10) > Number(21))
print(Number(10) <= Number(2))
print(Number(10) >= Number(20))
print(Number(2) <= Number(2))
print(Number(2) >= Number(2))
print(Number(2) == Number(2))
print(Number(2) == Number(3))

Output of this script will be:

This was actually easy to understand as it allowed us to remove redundant code in our class definition.

该脚本的输出为:

这实际上很容易理解,因为它允许我们在类定义中删除冗余代码。

In this lesson, we learned about various ways through which we can improve code reusability with functools module in Python.

在本课程中,我们学习了各种方法,可以通过这些方法来提高Python中functools模块的代码可重用性。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/17550/python-functools

python工具的功能介绍

python工具的功能介绍_Python功能工具相关推荐

  1. VS2017中自用部分插件的设置的翻译或功能介绍—— Viasfora功能介绍(二)

    Viasfora 彩虹括号,关键字高亮,转义符.占位符特殊颜色 4.2.188版本 官网/GitHub 说明 此篇为Viasfora的Github上Wiki中的官方功能介绍,其官网上的功能介绍也是指向 ...

  2. python scikit learn 关闭开源_Python机器学习工具:Scikit-Learn介绍与实践

    Scikit-learn 简介 官方的解释很简单: Machine Learning in Python, 用python来玩机器学习. 什么是机器学习 机器学习关注的是: 计算机程序如何随着经验积累 ...

  3. python实现计算器功能键介绍_python实现计算器功能

    本文实例为大家分享了python计算器的具体代码,供大家参考,具体内容如下 主要用到的工具是Python中的Tkinter库 比较简单 直接上图形界面和代码 引用Tkinter库 from tkint ...

  4. python的功能介绍_Python之int内部功能介绍

    int内部功能的介绍 type(): 1.基本数据类型使用type()函数时,得到相应的数据类型 a = 12 b = 12.01 c = "123" print(type(a)) ...

  5. python天气预报的功能介绍_python 实现天气预报功能

    中国国家气象局提供了获取所在城市天气预报信息的接口.通过这个接口,我们就可以获取天气信息了. 中国国家气象局天气预报接口总共提供了三个: http://www.weather.com.cn/data/ ...

  6. python天气预报的功能介绍_python实现智能语音天气预报

    本系统主要包括四个函数: 1.获取天气数据 1.输入要查询天气的城市 2.利用urllib模块向中华万年历天气api接口请求天气数据 3.利用gzip解压获取到的数据,并编码utf-8 4.利用jso ...

  7. python 微博自动点赞软件_Python微博工具人,每日一句英语自动发

    原标题:Python微博工具人,每日一句英语自动发 关注 来源 | 萝卜大杂烩(ID:luobodazahui) 如若转载请联系原公众号 最近在研究用 Python 来制作各个类别的机器人,今天先来分 ...

  8. python自动化工具之pywinauto(一)_python自动化工具之pywinauto(一)

    python自动化工具之pywinauto(一)python自动化工具之pywinauto一 pywinauto使用 一 判断程序的backend 二确定自动化入口点 三连接到进程 四 选择菜单项 p ...

  9. python q切换指定目录_Python小工具:3秒钟将视频转换为音频

    阅读文本大概需要 5 分钟. 作者 | pk 哥来源公众号 | Python知识圈 最近,有读者微信上私聊我,想让我写一篇视频批量转换成音频的文章,我答应了,周末宅家里把这个小工具做出来了. 这样,对 ...

最新文章

  1. IIS启动配置的一些命令
  2. telegram 组(groups) 和 频道(channels) 简介
  3. 【20120516】【中午】
  4. delphi 中listview的右键菜单处理
  5. YaoLingJump开发者日志(七)
  6. 流水灯c语言程序延时失败,用c8051f340做控制流水灯实验,程序会卡死在延时函数中 ,只要在那加延时函数程序就只能跑到那,代码如下...
  7. 软件工程电商系统数据库定义_某个电子商务系统项目的数据库设计
  8. centeros7安装mysql
  9. c/c++ 数组和指针
  10. C语言编译过程总结简版
  11. ubuntu9.10之grub.cfg详解
  12. java 新手入门电子书_3款针对初学者的免费Java电子书
  13. 汉王考勤管理软件mysql数据库配置_汉王考勤管理软件使用说明书介绍.pdf
  14. python笔记:太困了,读取并显示按行业分类的股票数据提提神
  15. div可拖拽移动js方法
  16. CentOS上安装 Docker-CE以及Docker 加速器配置
  17. layuiTable固定列
  18. 最简单的,安装flash插件
  19. 分支定界法 python_分支定界(Branchbound)算法
  20. STEM课程经典 | 美国小学标准教材1-5级套装,超过40州使用,让孩子在小学掌握科学思维...

热门文章

  1. Ubuntu 左边栏和顶栏都不见了,ctrl+alt+t 也调用不出terminal
  2. weblogic8.1在myeclipse中启动正常,在单独的weblogic中无法正常启动的解决方案.
  3. 几种经典的hash算法
  4. bus,device,driver三者关系
  5. # 语音信号处理基础(十)——梅尔倒谱系数
  6. [转载] [Python错误]NameError: name ‘name’ is not defined
  7. verilog系统任务之$random
  8. 【Linux】linux内核学习
  9. java 通过反射获取数组
  10. 使用百度编辑器--ueditor,后台接收提交编辑的内容,HTML不见了, 赋值不了,赋值之后,html暴露出来了??...