How/why do we use operator.abs

2019-02-18 11:06发布

问题:

In operators module we have a helper method operator.abs. But in python abs is already a function, and the only way I know to invoke the __abs__ method on an object is by function call anyway.

Is there some other fancy way I don't know about to take the absolute value of a number? If not, why does operator.abs exist in the first place, and what is an example where you would have to use it instead of plain old abs?

回答1:

abs(...)
    abs(a) -- Same as abs(a).

No, I don’t think there’s some other fancy way you don’t know about, or really any reason at all for this to be here at all except for consistency (since operator has methods for the other __operator__s).