sequence multiplied by -1
Emile van Sebille
emile at fenx.com
Fri Oct 1 12:55:25 EDT 2010
On 10/1/2010 9:44 AM Emile van Sebille said...
> 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.
Well, you can, but that's why you don't...
>>> class Guess:
... def __init__(self,val):
... self.val = val
... def __add__(self,other):
... try:
... other / 1
... return self.val + other
... except:
... return "%s%s" % (self.val,other)
...
>>> c = Guess(7)
>>> c+4
11
>>> c+"4"
'74'
Emile
>
> >>> 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