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

前端 未结 6 1544
日久生厌
日久生厌 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:47

    I believe that Python operators where inspired by C, where the + operator was introduced for symmetry (and also some useful hacks, see comments).

    In weakly typed languages such as PHP or Javascript, + tells the runtime to coerce the value of the variable into a number. For example, in Javascript:

       +"2" + 1
    => 3
       "2" + 1
    => '21'
    

    Python is strongly typed, so strings don't work as numbers, and, as such, don't implement an unary plus operator.

    It is certainly possible to implement an object for which +obj != obj :

    >>> class Foo(object):
    ...     def __pos__(self):
    ...        return "bar"
    ... 
    >>> +Foo()
    'bar'
    >>> obj = Foo()
    >>> +"a"
    

    As for an example for which it actually makes sense, check out the surreal numbers. They are a superset of the reals which includes infinitesimal values (+ epsilon, - epsilon), where epsilon is a positive value which is smaller than any other positive number, but greater than 0; and infinite ones (+ infinity, - infinity).

    You could define epsilon = +0, and -epsilon = -0.

    While 1/0 is still undefined, 1/epsilon = 1/+0 is +infinity, and 1/-epsilon = -infinity. It is nothing more than taking limits of 1/x as x aproaches 0 from the right (+) or from the left (-).

    As 0 and +0 behave differently, it makes sense that 0 != +0.

提交回复
热议问题