[Tutor] question about operator overloading

Dave Angel d at davea.name
Mon Mar 5 21:36:34 CET 2012


On 03/05/2012 03:16 PM, Albert-Jan Roskam wrote:
> Hi,
>
> I am extending a program for a hobby project where potentially huge spss files are read. I would like to add functionality to append files. I thought it would be nice and intuitive to overload + and += for this. The code below is a gross simplification, but I want to get the basics right. Is this the way how operator overloading is usually done?
>
>
> class Append(object):
>
>      def __init__(self, file1, file2=None):
>          """ file1 and file2 will actually be of a class of my own,
>          which has a readFile method that is a generator that returns
>          one record at a time """
>          self.file1 = file1
>          self.file2 = file2
>          self.merged = []
>
>      def __add__(self):
>          self.file1.extend(self.file2)
>          return self.file1
>
>      def __iadd__(self):
>          self.merged.extend(self.file1)
>          return self.merged
>         
>      def writerows(self):
>          rows = self.file1
>          for row in rows:
>              yield row
>
> # overloading '+'
> file1 = [[1, 2, 3], [4, 5, 6], [6, 6, 6]]       
> file2 = [[1, 2, 3]]
> app = Append(file1, file2)
> merged = app.file1 + app.file2 # 'merged'  will not actually hold data
> for line in app.writerows():
>      print line
>
> # overloading '+='
> files = [file1, file2]
> for i, f in enumerate(files):
>      if i == 0:
>          app = Append(f)
>          app.merged = f
>      else:
>          app.merged += f
> print app.merged
>

I hate to say it, but it's not even close.

When you say  app.file1 + app.file2,   you're not calling either of your 
special methods you defined in Append.  You're just adding the file1 and 
file2 attributes.  Since in your example these are lists, they do the 
usual thing.

Similarly, your app.merged += f  does NOT call your __iadd__() method.

Just what kind of an object is an Append object supposed to be?  Classes 
are usually for encapsulating data and behavior, not just to bundle up 
some functions.

Normally, you should be defining the __add__() and __iadd__() methods in the class that file1 and file2 are instances of.  So if you want to make a dummy example, start by defining a (single) class that holds just one of these.  Then create two instances, and try adding and +='ing the two instances.



DaveA


-- 

DaveA



More information about the Tutor mailing list