Operator Overloading Basics
Fredrik Lundh
fredrik at pythonware.com
Mon Aug 28 12:19:17 EDT 2006
Mohit Bhatt wrote:
> Hello,
>
> I just started out with python( couple of weeks).
>
> I have a query regarding Operator Overloading
>
> class c1:
> def __init__(self,value):
> self.data = value
> def __add__ (self,operand2):
> self.data += operand2
>
> obj1 = c1(1)
> obj1 + 10 # this works just fine
it modifies obj1, so I'm not sure I agree that it works fine. but sure,
it doesn't raise an exception.
> 10 + obj1 # throws exception
>
> Exception Details
>
> Traceback (most recent call last):
> File "<pyshell#38>", line 1, in -toplevel-
> 10+ obj1
>
> TypeError: unsupported operand type(s) for +: 'int' and 'instance'
>
> Q. What do I have to do to make the following line work?
>
> 10 + obj1
define "work".
if you want it to modify obj1 (and thus confuse the heck out of anyone
trying to use your class), implement __radd__.
if you want to create a sane accumulator, I recommend implementing +=
assignment instead, by overloading __iadd__ instead of __add__.
</F>
More information about the Python-list
mailing list