lazy arithmetic

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Aug 25 00:49:37 EDT 2006


At Friday 25/8/2006 00:36, pianomaestro at gmail.com wrote:

># This is what I have in mind:
>
>class Item(object):
>   def __add__(self, other):
>     return Add(self, other)

And this works fine... why make thinks complicated?

># 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

This doesn't make sense... __add__ should be a method, not a class...


>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 ?

x+y get translated to x.__add__(y)
x.__add__ is Add (the class), so Python calls Add, which means using 
it as a constructor with y as the (only) argument.
So you see in the __init__ method: self=a new instance of Add, a=y, 
b=None (default, as only one argument was provided).

If you really want to "inject" __add__ into the Item class, you could 
use a factory:

def AddFactory(a,b):
     return Add(a,b)
Item.__add__ = AddFactory

(but as you've said yourself, that's a bit crazy...)


Gabriel Genellina
Softlab SRL 


	
	
		
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas




More information about the Python-list mailing list