Using an operator to add in Python

前端 未结 5 2174
隐瞒了意图╮
隐瞒了意图╮ 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: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.

提交回复
热议问题