Question

Python 3 Here is my question. In clock.py, define class Clock which will perform some simple...

Python 3

Here is my question.

In clock.py, define class Clock which will perform some simple time operations. Write an initializer function for Clock that will take three arguments from the user representing hour (in 24-hour format), minutes, and seconds. Each of these parameters should have a reasonable default value. You should check that the provided values are within the legal bounds for what they represent and raise a ValueError if they are not.

if error_condition:
    raise ValueError("Descriptive error message")

Write instance method __str__ that will print the time in a nicely formatted fashion when the user calls print(clock_instance). The result of the __str__ method should primarily be readable.

>>> my_clock = clock.Clock(12, 34, 56)
>>> print(my_clock)
12:34:56
>>> my_clock = clock.Clock(1, 2, 3)
>>> print(my_clock)
01:02:03

Write instance method __repr__. The result of the __repr__ method should primarily be, above all, unambiguous. __repr__ should return a string that is intended more as a debugging aid for developers than anything else. And for that it needs to be as explicit as possible about what this object is. That’s why you’ll get a more elaborate result calling repr() on the object. __repr__'s output often the full module and class name:

>>> my_clock = clock.Clock(8, 56, 48)
>>> repr(my_clock)
'clock.Clock(8, 56, 48)'

Write instance method __add__ that will add the value of another Clock instance to the current one. Create and return a new Clock instance with the computed values.

>>> clock1 = clock.Clock(1, 34, 55)
>>> clock2 = clock.Clock(1, 7, 10)
>>> clock3 = clock1 + clock2
>>> print(clock3)
'02:42:05'

Add a class method, str_update, that will take as an argument a string in the form hh:mm:ss. In the method, parse the string into three integers and then set the Clock's time to the new values.

>>> my_clock = clock.Clock(8, 34)
>>> myclock.str_update("17:15:52")
>>> print(my_clock)
'17:15:52'
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python code

clock.py

class Clock:
  
   # constructor to initialize time values
   def __init__(self, hours=0, minutes=0, seconds=0):

       count = 0
       # check lower and upper bound for hours value
       if(hours>=0 and hours<=23):
           count+=1
       else:
           # raise value error
           raise ValueError("Hours should be between 0 and 23")

       # check lower and upper bound for minutes value
       if(minutes>=0 and minutes<=59):
           count+=1
       else:
           # raise value error
           raise ValueError("Minutes should be between 0 and 59")
  
       # check lower and upper bound for seconds value
       if(seconds>=0 and seconds<=59):
           count+=1
       else:
           # raise value error
           raise ValueError("Seconds should be between 0 and 59")

       if(count == 3):
           self.hours = hours
           self.minutes = minutes
           self.seconds = seconds

   def __str__(self):
      
       # return time in hh:mm:ss format
       return format(str(self.hours), "0>2")+":"+format(str(self.minutes), "0>2")+":"+format(str(self.seconds), "0>2")


   def __repr__(self):
      
       # return clock class object
       return "'clock.Clock(%s, %s, %s)'" % (str(self.hours), str(self.minutes), str(self.seconds))

   def __add__(self, other):

       # add seconds of object 1 and object 2
       seconds = self.seconds + other.seconds

       # add minutes of object 1 and object 2 and add seconds/60
       minutes = self.minutes + other.minutes + (seconds//60)
      
       # assign seconds%60 to seconds
       seconds = int(seconds%60)

       # add hours of object 1 and object 2 and add minutes/60
       hours = self.hours + other.hours + (minutes//60)

       # set minutes to minutes%60
       minutes = int(minutes%60)

       return Clock(hours, minutes, seconds)


   def str_update(self, string):
      
       # split the time string by :
       string = string.split(":")
      
       # update hours, minutes, and seconds values of the clock object
       self.hours = int(string[0])

       self.minutes = int(string[1])

       self.seconds = int(string[2])

main.py

# import clock
import clock

# create object clock1 for Clock class
clock1 = clock.Clock(1, 34, 55)

# create object clock2 for Clock class
clock2 = clock.Clock(1, 7, 10)

# add values of objects clock 1 and clock 2
clock3 = clock1 + clock2

# print value of resultant clock object
print(clock3)

# create object my_clock for Clock class
my_clock = clock.Clock(8, 34)

# update the value of clock object by passing string
my_clock.str_update("17:15:52")

# print the updated value of the clock object
print(my_clock)

# create object my_clock for Clock class
my_clock = clock.Clock(8, 56, 48)

# print object
print(repr(my_clock))

Sample Input/Output

Add a comment
Know the answer?
Add Answer to:
Python 3 Here is my question. In clock.py, define class Clock which will perform some simple...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Programming Assignment 1 Write a class called Clock. Your class should have 3 instance variables, one...

    Programming Assignment 1 Write a class called Clock. Your class should have 3 instance variables, one for the hour, one for the minute and one for the second. Your class should have the following methods: A default constructor that takes no parameters (make sure this constructor assigns values to the instance variables) A constructor that takes 3 parameters, one for each instance variable A mutator method called setHour which takes a single integer parameter. This method sets the value of...

  • In this practical task, you need to implement a class called MyTime, which models a time...

    In this practical task, you need to implement a class called MyTime, which models a time instance. The class must contain three private instance variables: hour, with the domain of values between 0 to 23. minute, with the domain of values between 0 to 59. second, with the domain of values between 0 to 59. For the three variables you are required to perform input validation. The class must provide the following public methods to a user: MyTime() Constructor. Initializes...

  • need help with this python program NOTE: You are NOT permitted to use ANY global variables....

    need help with this python program NOTE: You are NOT permitted to use ANY global variables. The use of any global variables will result in a deduction of 20%. NOTE: There is NO input or printing anywhere other than main! Significant points will be deducted if you violate this constraint! The following UML diagrams specify three classes. The RC_Filter class has a composition relationship with the Resistor and Capacitor classes. Your job is to implement these three classes as specified...

  • python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in...

    python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in addition to being a regular dictionary (using inheritance), it also defines an auxiliary/attribute dictionary that uses the bidict’s values as keys, associated to a set of the bidict’s keys (the keys associated with that value). Remember that multiple keys can associate to the same value, which is why we use a set: since keys are hashable (hashable = immutable) we can store them in...

  • Hello! This is C++. Q3. Write a program Define a Super class named Point containing: An...

    Hello! This is C++. Q3. Write a program Define a Super class named Point containing: An instance variable named x of type int. An instance variable named y of type int. Declare a method named toString() Returns a string representation of the point. Constructor that accepts values of all data members as arguments. Define a Sub class named Circle. A Circle object stores a radius (double) and inherit the (x, y) coordinates of its center from its super class Point....

  • please help me with this python code thank you 1. Write a Student class that stores...

    please help me with this python code thank you 1. Write a Student class that stores information for a Rutgers student. The class should include the following instance variables: (10 points) o id, an integer identifier for the student o lastName, a string for the student&#39;s last name o credits, an integer representing the number of course-credits the student has earned o courseLoad, an integer representing the current number of credits in progress Write the following methods for your Student...

  • For this question you must write a java class called Rectangle and a client class called...

    For this question you must write a java class called Rectangle and a client class called RectangleClient. The partial Rectangle class is given below. (For this assignment, you will have to submit 2 .java files: one for the Rectangle class and the other one for the RectangleClient class and 2 .class files associated with these .java files. So in total you will be submitting 4 files for part b of this assignment.) // A Rectangle stores an (x, y) coordinate...

  • This is a java homework for my java class. Write a program to perform statistical analysis...

    This is a java homework for my java class. Write a program to perform statistical analysis of scores for a class of students.The class may have up to 40 students.There are five quizzes during the term. Each student is identified by a four-digit student ID number. The program is to print the student scores and calculate and print the statistics for each quiz. The output is in the same order as the input; no sorting is needed. The input is...

  • This program will use the Random class to generate random temperatures (integers) between some minimum (inclusive)...

    This program will use the Random class to generate random temperatures (integers) between some minimum (inclusive) and some maximum (inclusive) values. You will need to calculate the minimum and maximum given a starting temperature integer and a possible change in temperature integer. (1) Copy the following method stub into your Temperature Predictor class and complete it according to the specifications described in the header comments. * Generates a random temperature (int) within a range when given the current temperature *...

  • JAVA programing Question 1 (Date Class):                                   &nbsp

    JAVA programing Question 1 (Date Class):                                                                                                     5 Points Create a class Date with the day, month and year fields (attributes). Provide constructors that: A constructor that takes three input arguments to initialize the day, month and year fields. Note 1: Make sure that the initialization values for the day, month and year fields are valid where the day must be between 1 and 31 inclusive, the month between 1 and 12 inclusive and the year a positive number. Note 2:...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT