使用运算符添加Python

使用运算符添加Python

本文介绍了使用运算符添加Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

operator.add(a, b)

我很难理解它的作用.运算符类似于+-*/,那么operator.add(a, b)的作用是什么,您将如何在程序中使用它?

I'm having trouble understanding what this does. An operator is something like +-*/, so what does operator.add(a, b) do and how would you use it in a program?

推荐答案

操作员函数可让您动态选择操作.

Operator functions let you pick operations dynamically.

它们与运算符具有相同的作用,因此operator.add(a, b)a + b的作用完全相同,但是您现在可以抽象地使用这些运算符.

They do the same thing as the operator, so operator.add(a, b) does the exact same thing as a + b, but you can now use these operators in abstract.

例如:

import operator, random

ops = [operator.add, operator.sub]
print(random.choice(ops)(10, 5))

上面的代码将随机地将两个数字相加或相减.因为运算符可以以函数形式应用,所以您还可以将这些函数存储在变量(列表,字典等)中,并根据您的代码间接使用它们.您可以将它们传递给map()reduce()partial等,等等,等等.

The above code will randomly either add up or subtract the two numbers. Because the operators can be applied in function form, you can also store these functions in variables (lists, dictionaries, etc.) and use them indirectly, based on your code. You can pass them to map() or reduce() or partial, etc. etc. etc.

这篇关于使用运算符添加Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 23:24