Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # An exercise in OOP and Time calculations
- # Given a Movie's start time and duration, compute and print the end time.
- # We can assume the movie will end before midnight!
- # *** Dec 20th: I moved the definition of the duration() method to the end of the class
- # just to prove that it can be referred to within the class before it is defined. No problem.
- class Time(object): # this defines a "prototype" of an object
- def start(self, hh, mm, ss): # This is another 'method' within the Time class
- # Establish the start time of the movie in seconds.
- # We can do it in a simple manner by adding the start time to a zero base time
- # (as we already have such a function)
- self.seconds = 0 # Establish a zero base starting time
- self.duration(hh, mm, ss) # Add the start time to the base (so base now equals start)
- def calculate(self): # This is a third 'method' within the Time class
- # convert the end time (which is in seconds) to hours, minutes, seconds
- mm, ss = divmod(self.seconds, 60) # divmod() is a built-in Python function that ...
- hh, mm = divmod(mm, 60) # ... computes the quotient and remainder of a division
- # Convert the hours minutes and seconds to strings, with zero-fill
- self.endtime = str(hh).zfill(2) + ':' + str(mm).zfill(2) + ':' + str(ss).zfill(2)
- # We'll start by defining a 'method' that adds a time in hours, minutes, seconds
- # to a base time held in seconds only
- def duration(self, hh, mm, ss):
- self.seconds += hh * 3600 # add 3600 seconds for every hour
- self.seconds += mm * 60 # and 60 seconds for every minute
- self.seconds += ss # finally add in the seconds
- movie = Time() # Instantiate an object called 'movie' of class 'Time'
- movie.start(21, 30, 30) # Pass the movie start time to our movie object
- movie.duration(1, 50, 40) # Pass the movie duration to our movie object
- movie.calculate() # Call the movie method that computes the end time
- print(movie.endtime) # Print the result
- # 23:21:10
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement