一个类实例 [Core Programming]



[root@lvdbing python]# cat Time2.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# vim: set ai cindent et sw=4 ts=4 nowrap foldmethod=marker:
class Time:
    '''Class Time with accessor methods'''
    def __init__(self):
        '''Time constructor initializes each data member to zero'''
        self._hour = 0
        self._minute = 0
        self._second = 0
    def setTime(self, hour, minute, second):
        '''Set values of hour, minute, and second'''
        self.setHour(hour)
        self.setMinute(minute)
        self.setSecond(second)
    def setHour(self, hour):
        '''Set hour value'''
        if 0 = hour  24:
            self._hour = hour
        else:
            raise ValuesError, "Invalid hour value: %d" % hour
    def setMinute(self, minute):
        '''Set minute value'''
        if 0 = minute  60:
            self._minute = minute
        else:
            raise ValueError, "Invalid minute value: %d" % minute
    def setSecond(self, second):
        '''Set second value'''
        if 0 = second  60:
            self._second = second
        else:
            raise ValueError, "Invalid second value: %d" % second
    def getHour(self):
        '''Get hour value'''
        return self._hour
    def getMinute(self):
        '''Get minute value'''
        return self._minute
    def getSecond(self):
        '''Get second value'''
        return self._second
    def printMilitary(self):
        '''Prints Time object in military format'''
        print "%.2d:%.2d:%.2d" % (self._hour, self._minute, self._second),
         
    def printStandard(self):
        '''Prints Time object in standard format'''
        standardTime = ""
        if self._hour == 0 or self._hour == 12:
            standardTime += "12:"
        else:
            standardTime += "%d:" % (self._hour % 12)
            
        standardTime += "%.2d:%.2d" % (self._minute, self._second)
        if self._hour  12:
            standardTime += " AM"
        else:
            standardTime += " PM"
        print standardTime,

[root@lvdbing python]# cat fig08_01.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# vim: set ai cindent et sw=4 ts=4 nowrap foldmethod=marker:
from Time2 import Time
time1 = Time()
print "The initial military time is",
time1.printMilitary()
print "\nThe initial standard time is",
time1.printStandard()
   
print "\n"
time1.setTime(13, 27, 16)
print "The initial military time is",
time1.printMilitary()
print "\nThe initial standard time is",
time1.printStandard()
print "\n"
time1.setHour(6)
time1.setMinute(9)
time1.setSecond(10)
print "The initial military time is",
time1.printMilitary()
print "\nThe initial standard time is",
time1.printStandard()

[root@lvdbing python]# ./fig08_01.py
The initial military time is 00:00:00
The initial standard time is 12:00:00 AM
The initial military time is 13:27:16
The initial standard time is 1:27:16 PM
The initial military time is 06:09:10
The initial standard time is 6:09:10 AM