[Python-Dev] ++x oddnes
Guido van Rossum
guido@python.org
Mon, 13 Aug 2001 10:02:21 -0400
> How? ++x compiles to
>
> LOAD_FAST x
> UNARY_POSITIVE
> UNARY_POSITIVE
>
> I don't see any incrementing going on...
I'm guessing that MAL used a perverse implementation trick, where for
a certain *mutable* counter type '+x' returns an object that contains
a reference to x, and the unary plus operation on *that* object
increments the counter it references.
class C:
def __init__(self):
self.counter = 0
def inc(self):
self.counter += 1
def __str__(self):
return str(self.counter)
def __pos__(self):
return Ref(self)
class Ref:
def __init__(self, arg):
self.referent = arg
def __pos__(self):
self.referent.inc()
return self.referent
a = C()
print a # 0
print ++a # 1
print a # 1
Twisted, sick, call it what you want -- but please don't get used to
this. The likelihood that I'll ever add a ++ operator is very small,
but not zero. :-)
--Guido van Rossum (home page: http://www.python.org/~guido/)