Using an operator to add in Python

一曲冷凌霜 提交于 2019-12-11 03:35:49

问题


Consider:

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?


回答1:


Operator functions let you pick operations dynamically.

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.

Take for example:

import operator, random

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

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.




回答2:


As operator.add is a function and you can pass argument to it, it's for the situations where you can not use statements like a+d, like the map or itertools.imap functions. For better understanding, see the following example:

>>> import operator
>>> from itertools import imap
>>> list(imap(operator.add,[1,3],[5,5]))
[6, 8]



回答3:


It does the same, it's just a function version of the operator in the Python operator module. It returns the result, so you would just it like this:

result = operator.add(a, b)

This is functionally equivalent to

result = a + b



回答4:


It literally is how the + operator is defined. Look at the following example

class foo():
    def __init__(self, a):
        self.a = a
    def __add__(self, b):
        return self.a + b

>>> x = foo(5)
>>> x + 3
8

The + operator actually just calls the __add__ method of the class

The same thing happens for native Python types,

>>> 5 + 3
8
>>> operator.add(5,3)
8

Note that since I defined my __add__ method, I can also do

>>> operator.add(x, 3)
8



回答5:


For the first part of your question, checkout the source for operator.add. It does exactly as you'd expect; adds two values together.

The answer to part two of your question is a little tricky.

They can be good for when you don't know what operator you'll need until run time. Like when the data file you're reading contains the operation as well as the values:

# warning: nsfw
total = 0
with open('./foo.dat') as fp:
    for line in fp:
        operation, first_val, second_val = line.split()
        total += getattr(operator, operation)(first_val, second_val)

Also, you might want to make your code cleaner or more efficient (subjective) by using the operator functions with the map built-in as the example shows in the Python docs:

orig_values = [1,2,3,4,5]
new_values = [5,4,3,2,1]
total = sum(map(operator.add, orig_values, new_values))

Those are both convoluted examples which usually means that you probably won't use them except in extraordinary situations. You should really know that you need these functions before you use them.



来源:https://stackoverflow.com/questions/27278872/using-an-operator-to-add-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!