Operator overloading for part of an object

Scherer, Bill Bill.Scherer at VerizonWireless.com
Wed May 23 11:54:19 EDT 2001


On Wed, 23 May 2001, David Humphrey wrote:

> I've been using operator overloading in both C++ and Python for some time
> now and have run into a situation I never thought about before.  How do you
> overload an operator that operates on some of the data for pair of instances
> and return only that modified data to the resulting instance?
>
> Here's a simple example.  Assume class C stores a name and a float and
> defines the __add__ operator.  I want to be able to write expressions like:
>
> c = a + b
>
> so that the float portion of instance c is the sum of the float portions of
> instances a and b.  Here's some code that specifies all this more exactly:
>
> #==========================================
> import sys
>
> class C:
>    def __init__(self,aname,somedata=0.0):
>       self.name = aname
>       self.data = somedata
>    def __add__(self,b):
>       return self.data + b.data
>    def report(self):
>       print 'name = %s, data = %d\n' % (self.name,self.data)

I think you need __add__ to return an instance of C:

  def __add__(self, other):
    return C(self.name, self.data + other.data)

In your example c is reassigned to a float after the add, so it's no
longer an instance of C.  With __add__ returning an instance of C, c in
you example should work as you require (all untested, of course...)

> #
> # main code
> #
> a = C('instance a',1.0)
> a.report()
> b = C('instance b',2.0)
> b.report()
> c = C('instance c')
> c.report()
>
> c = a + b
> c.report()
>
> #==========================================
>
> In this case, I want c.report() to tell me
>
> name = c, data = 3.0
>
> but, instead, I get
>
> $ python ./test.py
> name = instance a, data = 1
>
> name = instance b, data = 2
>
> name = instance c, data = 3
>
> Traceback (most recent call last):
>   File "./test.py", line 26, in ?
>     c.report()
> AttributeError: 'float' object has no attribute 'report'
>
>
> OK, I understand why it behaves this way, but I don't see how to preserve
> c.name while updating c.data with the computed value.  I konw I need to
> overload the '=' operator, but don't see facilities in python to do that.
>
> Thanks in advance for your advice.
>
> David L. Humphrey
> Manager, Software Development
> Bell Geospace, Inc
>
>
>

William K. Scherer
Sr. Member of Applications Staff - Verizon Wireless
Bill.Scherer_at_VerizonWireless.com





More information about the Python-list mailing list