Behaviour of increment and decrement operators in Python

后端 未结 9 1852
无人共我
无人共我 2020-11-22 05:26

I notice that a pre-increment/decrement operator can be applied on a variable (like ++count). It compiles, but it does not actually change the value of the vari

9条回答
  •  旧巷少年郎
    2020-11-22 05:59

    While the others answers are correct in so far as they show what a mere + usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.

    To be exact, +x evaluates to x.__pos__() and ++x to x.__pos__().__pos__().

    I could imagine a VERY weird class structure (Children, don't do this at home!) like this:

    class ValueKeeper(object):
        def __init__(self, value): self.value = value
        def __str__(self): return str(self.value)
    
    class A(ValueKeeper):
        def __pos__(self):
            print 'called A.__pos__'
            return B(self.value - 3)
    
    class B(ValueKeeper):
        def __pos__(self):
            print 'called B.__pos__'
            return A(self.value + 19)
    
    x = A(430)
    print x, type(x)
    print +x, type(+x)
    print ++x, type(++x)
    print +++x, type(+++x)
    

提交回复
热议问题