简体   繁体   中英

Why do we need operator functions in python?

Why would one use operator s in python when we have almost all of them available inline such as [/,*,-,+,<,>,...]?

When would we need to use these operator functions as opposed to the inline operators?

As an example of why you might like to be able to call an operator as a function, consider the following code:

    if op == "+":
        return num1 + num2
    elif op == "-":
        return num1 - num2
    elif op == "*":
        return num1 * num2
    else:
        raise ValueError(f"invalid operator {op}")

With operator this can be written more easily as:

    return {
        "+": operator.add,
        "-": operator.sub,
        "*": operator.mul,
    }[op](num1, num2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM