lazy arithmetic
Peter Otten
__peter__ at web.de
Fri Aug 25 04:05:05 EDT 2006
pianomaestro at gmail.com wrote:
> # This is what I have in mind:
>
> class Item(object):
> def __add__(self, other):
> return Add(self, other)
>
> class Add(Item):
> def __init__(self, a, b):
> self.a = a
> self.b = b
>
> a = Item()
> b = Item()
>
> c = a+b
>
> # Now, I am going absolutely crazy with this idea
> # and using it in a big way. So I'm looking at
> # automating the process. As a first step,
> # I thought maybe this would work:
>
> class Item(object):
> pass
>
> class Add(Item):
> def __init__(self, a, b=None):
> print self, a, b
> self.a = a
> self.b = b
>
> Item.__add__ = Add
>
> x = Item()
> y = Item()
>
> print x, y
>
> c = x+y
>
> # This time, the Add constructor gets only the first two arguments:
> "self" and "y".
> # So, what happened to "x" ? Is this some kind of property voodoo going
> on ?
Indeed. Read up on descriptors:
http://users.rcn.com/python/download/Descriptor.htm
The following seems to work:
from new import instancemethod
class Add:
class __metaclass__(type):
def __get__(self, inst, cls):
if inst is None:
return cls
return instancemethod(cls, inst, cls)
def __init__(self, a, b=None):
self.a = a
self.b = b
def __str__(self):
return "%s(%s, %s)" % (self.__class__.__name__, self.a, self.b)
Add.__add__ = Add
print Add(1, 2) + 42
but makes the simple
def __add__(self, other):
return Add(self, other)
all the more attractive.
Peter
More information about the Python-list
mailing list