>>> d.characters[0].underline = True
>>> print(d.string)
_he*l*lo
W/o_rld
www.it-ebooks.info
Chapter 5
[
153
]
As expected, whenever we print the string, each bold character is preceded by a
*
character, each italic character by a
/
character, and each underlined character
by a
_
character. All our functions seem to work, and we can modify characters in
the list after the fact. We have a working rich text document object that could be
plugged into a proper user interface and hooked up with a keyboard for input and
a screen for output. Naturally, we'd want to display real bold, italic, and underlined
characters on the screen, instead of using our
__str__
method, but it was sufficient
for the basic testing we demanded of it.
Exercises
We've looked at various ways that objects, data, and methods can interact with each
other in an object-oriented Python program. As usual, your first thoughts should
be how you can apply these principles to your own work. Do you have any messy
scripts lying around that could be rewritten using an object-oriented manager?
Look through some of your old code and look for methods that are not actions.
If the name isn't a verb, try rewriting it as a property.
Think about code you've written in any language. Does it break the DRY principle?
Is there any duplicate code? Did you copy and paste code? Did you write two
versions of similar pieces of code because you didn't feel like understanding the
original code? Go back over some of your recent code now and see whether you
can refactor the duplicate code using inheritance or composition. Try to pick a
project you're still interested in maintaining; not code so old that you never want
to touch it again. It helps keep your interest up when you do the improvements!
Now, look back over some of the examples we saw in this chapter. Start with the
cached web page example that uses a property to cache the retrieved data. An
obvious problem with this example is that the cache is never refreshed. Add a
timeout to the property's getter, and only return the cached page if the page has
been requested before the timeout has expired. You can use the
time
module
(
time.time() - an_old_time
returns the number of seconds that have elapsed
since
an_old_time
) to determine whether the cache has expired.
Now look at the inheritance-based
ZipProcessor
. It might be reasonable to use
composition instead of inheritance here. Instead of extending the class in the
ZipReplace
and
ScaleZip
classes, you could pass instances of those classes into the
ZipProcessor
constructor and call them to do the processing part. Implement this.
www.it-ebooks.info
When to Use Object-oriented Programming
Do'stlaringiz bilan baham: |