Using an operator to add in Python

前端 未结 5 2142
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 13:35

Consider:

operator.add(a, b)

I\'m having trouble understanding what this does. An operator is something like +-*/, so what doe

相关标签:
5条回答
  • 2021-01-06 13:46

    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]
    
    0 讨论(0)
  • 2021-01-06 13:46

    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
    
    0 讨论(0)
  • 2021-01-06 13:46

    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.

    0 讨论(0)
  • 2021-01-06 13:47

    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
    
    0 讨论(0)
  • 2021-01-06 13:54

    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.

    0 讨论(0)
提交回复
热议问题