What's the purpose of the + (pos) unary operator in Python?

前端 未结 6 1539
日久生厌
日久生厌 2020-11-27 18:04

Generally speaking, what should the unary + do in Python?

I\'m asking because, so far, I have never seen a situation like this:

+obj !=          


        
6条回答
  •  [愿得一人]
    2020-11-27 18:40

    __pos__() exists in Python to give programmers similar possibilities as in C++ language — to overload operators, in this case the unary operator +.

    (Overloading operators means give them a different meaning for different objects, e. g. binary + behaves differently for numbers and for strings — numbers are added while strings are concatenated.)

    Objects may implement (beside others) these emulating numeric types functions (methods):

        __pos__(self)             # called for unary +
        __neg__(self)             # called for unary -
        __invert__(self)          # called for unary ~
    

    So +object means the same as object.__pos__() — they are interchangeable.

    However, +object is more easy on the eye.

    Creator of a particular object has free hands to implement these functions as he wants — as other people showed in their real world's examples.

    And my contribution — as a joke: ++i != +i in C/C++.

提交回复
热议问题