27.07.2013 Views

Deitel - Python, How To Program.pdf

Deitel - Python, How To Program.pdf

Deitel - Python, How To Program.pdf

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

pythonhtp1_07.fm Page 238 Saturday, December 8, 2001 2:29 PM<br />

238 Object-Based <strong>Program</strong>ming Chapter 7<br />

<strong>Python</strong> 2.2b2 (#26, Nov. 16 2001, 11:44:11) [MSC 32 bit (Intel)] on<br />

win32<br />

Type "help", "copyright", "credits" or "license" for more information.<br />

>>><br />

>>> raise ValueError, "This is an error message"<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

ValueError: This is an error message<br />

Fig. Fig. 7.8 7.8 Raising an exception.<br />

Lines 45–58 contain the get methods for class Time. Clients use these methods<br />

(getHour, getMinute and getSecond) to retrieve the values of an attributes _hour,<br />

_minute and _second, respectively. The remainder of the class definition does not<br />

differ from the previous definition we presented.<br />

Software Engineering Observation 7.8<br />

If a class provides access methods for its data, clients should use only access methods to retrieve/modify<br />

data. This “agreement” between class and client helps maintain data in a consistent<br />

state. 7.8<br />

Software Engineering Observation 7.9<br />

The class designer need not provide set or get methods for each data item; these capabilities<br />

should be provided only when appropriate. If the service is appropriate for clients, that service<br />

should be provided in the class’s interface. 7.9<br />

Software Engineering Observation 7.10<br />

Every method that modifies the data of an object should ensure that the data remains in a<br />

consistent state. 7.10<br />

Figure 7.9 contains a driver for modified class Time. A driver is a program that tests<br />

a class’s interface. Lines 4–6 import class Time from module Time2 and create an<br />

object of the class. Lines 9–12 call methods printMilitary and printStandard to<br />

display the initial time values of the object.<br />

1 # Fig. 7.9: fig07_09.py<br />

2 # Driver to test class TimeControl.<br />

3<br />

4 from Time2 import Time<br />

5<br />

6 time1 = Time()<br />

7<br />

8 # print initial time<br />

9 print "The initial military time is",<br />

10 time1.printMilitary()<br />

11 print "\nThe initial standard time is",<br />

12 time1.printStandard()<br />

Fig. Fig. 7.9 7.9 Access methods called to change data. (Part 1 of 2.)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!