[Tutor] question about operator overloading
d at davea.name
Mon Mar 5 22:25:33 CET 2012
On 03/05/2012 04:10 PM, Albert-Jan Roskam wrote:
> Hi Dave,
> aha! Good thing I asked. ;-) I've indeed been thinking where this __add__ method should live. The program as it is now has a Generic class, a Reader class and a Writer class. I thought an Append class was appropriate because it uses Reader and Writer (and probably also Generic) methods and the data is from multiple files. It reads a bunch of files (even though the term 'reading' is more a conceptual term here, as none of the data will be held in memory), appends them (__add__), and writes them to one merged file. Doesn't adding __add__ change the responsibility from 'thou shallt read one and only one file' into something less precise?
> So if I understand you correctly, the following pseudocode is better?
> merged = Reader.readFile(somefile1) + Reader.readFile(somefile2)
> # ..which is the same as: Reader.readFile(somefile1).__add__(Reader.readFile(somefile2))
> for line in merged:
> Maybe this is why my 'top-down code' (what I posted earlier) and my 'bottom-up code' (some code that I wrote earlier) don't add up (pun intended!). In the bottom-up code there was no need for an Append class!
Please don't top-post. We've now lost all the context of what happened
You still don't get it. If you're going to add objects, they should be
objects that represent what's being added. So the objects are of type
MyFile, not type Reader, whatever that is. Reader and Writer sounds
like a java approach.
So you combine two files something like this:
file1 = MyFile(whatever, moreargs)
file2 = MyFile(whateverelse, lessargs)
file1 += file2
that last line will call the method __iadd__() of class MyFile. Self
will be file1, and the other parameter will be file2. By convention,
it'd add file2 to the end of already-existing file1.
It's not clear what __add__() should mean for physical files. It builds
something (MyFile instance) that represents two of them, but there's no
way to assign a filename to it, except after the fact. So it might be
an in-memory equivalent (eg. a list). It should NOT just extend the
first file. Generally, it shouldn't modify either of its arguments.
By the way, you could have learned a lot in your original example by
just adding print statements in the two methods.
More information about the Tutor