[Tutor] question about operator overloading

Albert-Jan Roskam fomcl at yahoo.com
Mon Mar 5 21:16:13 CET 2012


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

 
Thank you in advance!


Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120305/8c660613/attachment-0001.html>


More information about the Tutor mailing list