Advertisement
acclivity

pyMovieDuration

Dec 10th, 2021 (edited)
906
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.19 KB | None | 0 0
  1. # An exercise in OOP and Time calculations
  2. # Given a Movie's start time and duration, compute and print the end time.
  3. # We can assume the movie will end before midnight!
  4.  
  5. # *** Dec 20th: I moved the definition of the duration() method to the end of the class
  6. # just to prove that it can be referred to within the class before it is defined. No problem.
  7.  
  8. class Time(object):             # this defines a "prototype" of an object
  9.  
  10.     def start(self, hh, mm, ss):        # This is another 'method' within the Time class
  11.         # Establish the start time of the movie in seconds.
  12.         # We can do it in a simple manner by adding the start time to a zero base time
  13.         # (as we already have such a function)
  14.         self.seconds = 0                # Establish a zero base starting time
  15.         self.duration(hh, mm, ss)       # Add the start time to the base (so base now equals start)
  16.  
  17.     def calculate(self):                # This is a third 'method' within the Time class
  18.         # convert the end time (which is in seconds) to hours, minutes, seconds
  19.         mm, ss = divmod(self.seconds, 60)       # divmod() is a built-in Python function that ...
  20.         hh, mm = divmod(mm, 60)                 # ... computes the quotient and remainder of a division
  21.         # Convert the hours minutes and seconds to strings, with zero-fill
  22.         self.endtime = str(hh).zfill(2) + ':' + str(mm).zfill(2) + ':' + str(ss).zfill(2)
  23.  
  24.     # We'll start by defining a 'method' that adds a time in hours, minutes, seconds
  25.     # to a base time held in seconds only
  26.     def duration(self, hh, mm, ss):
  27.         self.seconds += hh * 3600       # add 3600 seconds for every hour
  28.         self.seconds += mm * 60         # and 60 seconds for every minute
  29.         self.seconds += ss              # finally add in the seconds
  30.  
  31. movie = Time()                  # Instantiate an object called 'movie' of class 'Time'
  32. movie.start(21, 30, 30)         # Pass the movie start time to our movie object
  33. movie.duration(1, 50, 40)       # Pass the movie duration to our movie object
  34. movie.calculate()               # Call the movie method that computes the end time
  35. print(movie.endtime)            # Print the result
  36.  
  37. # 23:21:10
  38.  
  39.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement