[
145
]
scaled = im.resize((640, 480))
scaled.save(str(filename))
if __name__ == "__main__":
ScaleZip(*sys.argv[1:4]).process_zip()
Look how
simple this class is! All that work we did earlier paid off. All we do is
open each file (assuming that it is an image; it will unceremoniously crash if a file
cannot be opened), scale it, and save it back. The
ZipProcessor
class takes care of
the zipping and unzipping without any extra work on our part.
Case study
For this case study, we'll try to delve further into the question, "when should I choose
an object versus a built-in type?" We'll be modeling a
Document
class that might be
used in a text editor or word processor. What objects, functions, or properties should
it have?
We might start with a
str
for the
Document
contents, but in Python, strings aren't
mutable (able to be changed). Once a
str
is defined, it is forever. We can't insert
a character into it or remove one without creating a brand new string object. That
would be leaving a lot of
str
objects taking up memory until Python's garbage
collector sees fit to clean up behind us.
So, instead of a string, we'll use a list of characters, which we can modify at will. In
addition, a
Document
class would need to know the current cursor position within
the list, and should probably also store a filename for the document.
Real text editors use a binary-tree based data structure called a
rope
to model their document contents. This book's title isn't
"advanced data structures", so if you're interested in learning more
about this fascinating topic, you may want to search the web for the
rope data structure.
Now, what methods should it have? There are a lot of things we might want to
do to a text document, including inserting, deleting, and selecting characters, cut,
copy, paste, the selection, and saving or closing the document. It looks like there
are copious amounts of both data and behavior, so it makes sense to put all this
stuff into its own
Document
class.
A pertinent question is: should this class be composed of a bunch of basic Python
objects such as
str
filenames,
int
cursor positions, and a
list
of characters? Or
should some or all of those things be specially defined objects in their own right?
What about individual lines and characters, do they need to have classes of their own?
www.it-ebooks.info
When to Use Object-oriented Programming
Do'stlaringiz bilan baham: |