What does a plus sign do in front of a variable in Python?

后端 未结 2 1407
醉话见心
醉话见心 2021-01-17 10:02

There\'s the following bit of Python code in a project I have to maintain:

# If the `factor` decimal is given, compute new price and a delta
factor = +factor         


        
相关标签:
2条回答
  • 2021-01-17 10:09

    I ran into this same problem when I wrongly assumed that Python must support the C increment (++) operator; it doesn't! Instead, it applies the plus-sign operator (+) twice! Which does nothing twice, I soon learned. However, because "++n" looked valid... not flagged as a syntax error... I created a terrible bug for myself.

    So unless you redefine what it does, unary + actually does nothing. Unary - changes from positive to negative and vice-versa, which is why "--n" is also not flagged as a syntax error but it also does nothing.

    0 讨论(0)
  • 2021-01-17 10:14

    What that plus sign does depends on what it's defined to do by the result of that expression (that object's __pos__() method is called). In this case, it's a Decimal object, and the unary plus is equivalent to calling the plus() method. Basically, it's used to apply the current context (precision, rounding, etc.) without changing the sign of the number. Look for a setcontext() or localcontext() call elsewhere to see what the context is. For more information, see here.

    The unary plus is not used very often, so it's not surprising this usage is unfamiliar. I think the decimal module is the only standard module that uses it.

    0 讨论(0)
提交回复
热议问题