sequence multiplied by -1

Emile van Sebille emile at fenx.com
Fri Oct 1 12:44:34 EDT 2010


On 10/1/2010 5:56 AM Antoon Pardon said...

> Someone provides you with a library of functions that act on sequences.
> They rely on the fact that '+' concatenates.
>
> Someone else provides you with a library of functions that act on
> numbers. They rely on the fact that '+' provides addition.
>

But you can do that now -- you just can't have a class that provides 
_both_ behaviors.

 >>> class Addem:
...   def __init__(self,val):
...     self.val = val
...   def __add__(self,other):
...     return self.val + other
...
 >>> class Concatem:
...   def __init__(self,val):
...     self.val = val
...   def __add__(self,other):
...     return "%s%s" % (self.val,other)
...
 >>>
 >>> a = Addem(7)
 >>> a+4
11
 >>>
 >>> b = Concatem(7)
 >>> b+4
'74'


Emile




More information about the Python-list mailing list