Python ++ Operator?

Chris Torek nospam at torek.net
Fri Jul 15 22:48:46 CEST 2011


In article <mailman.1055.1310716536.1164.python-list at python.org>
Chris Angelico  <rosuav at gmail.com> wrote:
>2011/7/15 Rafael Durán Castañeda <rafadurancastaneda at gmail.com>:
>> Hello all,
>> What's the meaning of using i++? Even, does exist ++ operator in python?
>
>++i is legal Python but fairly useless. It's the unary + operator,
>applied twice. It doesn't increment the variable.

Well...

    class Silly:
        def __init__(self, value):
            self.value = value
            self._pluscount = 0
        def __str__(self):
            return str(self.value)
        def __pos__(self):
            self._pluscount += 1
            if self._pluscount == 2:
                self.value += 1
                self._pluscount = 0
            return self

    def main():
        i = Silly(0)
        print('initially, i = %s' % i)
        print('plus-plus i = %s' % ++i)
        print('finally, i = %s' % i)

    main()

:-)

(Of course, +i followed by +i *also* increments i...)
-- 
In-Real-Life: Chris Torek, Wind River Systems
Intel require I note that my opinions are not those of WRS or Intel
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W)  +1 801 277 2603
email: gmail (figure it out)      http://web.torek.net/torek/index.html



More information about the Python-list mailing list