Using an operator to add in Python

前端 未结 5 2177
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题