PYTHON   107

Time

Guest on 15th June 2022 05:18:44 AM

  1. class Time(object):
  2.     def __init__(self, hour, min):
  3.         self.setHour(hour)
  4.         self.setMin(min)
  5.  
  6.     def setHour(self, hour):
  7.         print("setting hour")
  8.         if 0 <= hour <= 23:
  9.             self._hour = hour
  10.         else:
  11.             raise ValueError("Invalid hour value: %d" % hour)
  12.  
  13.     def setMin(self, min):
  14.         if 0 <= min <= 59:
  15.             self._min = min
  16.         else:
  17.             raise ValueError("Invalid min value: %d" % min)
  18.  
  19.     def getHour(self):
  20.         print("getting hour")
  21.         return self._hour
  22.  
  23.     def getMin(self):
  24.         return self._min
  25.  
  26.     def print24h(self):
  27.         print("{:2}:{:2}".format(self.getHour(),
  28.                                  self.getMin()))
  29.     def print12h(self):
  30.         if self.getHour() < 12:
  31.             ampm = "am"
  32.         else:
  33.             ampm = "pm"
  34.  
  35.         print("{:2}:{:2} {}".format(self.getHour() % 12,
  36.                                     self.getMin(), ampm))
  37.  
  38.     hour = property(getHour, setHour)
  39.  
  40. if __name__ == "__main__":
  41.     t = Time(15, 45)
  42.  
  43.     print("print as 24h: "),
  44.     t.print24h()
  45.     print("print as 12h: "),
  46.     t.print12h()
  47.     print("that is %d hours and %d minutes" % \
  48.           (t.getHour(), t.getMin()))

Raw Paste


Login or Register to edit or fork this paste. It's free.