Operator overloading for part of an object

David Humphrey dhumphrey at pdqdot.net
Wed May 23 11:27:46 EDT 2001


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





More information about the Python-list mailing list