Skip to main content

Section 1.19 HW10

Creating classes

Exercises Exercises

1. Defining Classes.

    Previously, you have used built-in types in Python like dict, str, and list. Each of these types comes with its own methods, such as keys, lower,Β and append.
    Every object has a typethatΒ indicates which class the object belongs to. The purpose of the class definition is to specify the instance variablesΒ (aka data, attributes) and methods (aka functions) that each object belonging to the class will have.
    For example, in real life, every carhas attributes such as make, model, and current odometer. And every reasonable car has available methods such as start engine, shift transmission, and honk horn.
    Our goal in this assignment is to learn how to create new data types by defining our ownΒ classes.
  • True.

  • False.

2.

3.

4.

5.

6.

7.

8.

Based on your previous answers, how does the number of arguments for each method calldiffer from the number of parameters specified in the method’s definition?
  • There is one less argument.
  • Yes! We do not provide an argument for the "self" parameter.
  • There is no difference.
  • Review your answers to the previous two questions.
  • There is one less parameter.
  • Review your answers to the previous two questions.

9. Initializing New Instances of the Class.

Consider the following class definition.
class Timer:
    """ A class that represents a timer. """
    def __init__(self):
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
Which of these methods is responsible for initializing the instance variables (attributes) of a new instance?
  • __init__
  • __str__
  • print_with_labels

10. Creating Objects.

Consider the following class definition.
class Timer:
    """ A class that represents a timer. """
    def __init__(self):
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
Which of the following lines of code will create a new Timer object set to 0 seconds, 0 minutes, and 0 hours, and assign it to the variable timer1?
  • timer1 = Timer()
  • timer1 = Timer(0, 0, 0)
  • timer1.__init__(self)
  • timer1.Timer()
  • timer1.Timer(0, 0, 0)
  • timer1.__init__()

11. Calling Methods 1.

Consider the following class definition.
class Timer:
    """ A class that represents a timer. """
    def __init__(self):
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
Recall: The __str__method returns the string representation of the object. ThisΒ methodΒ is activated (automatically!) whenever print() or str() is invoked on an object. (Like all the other methods whose names are surrounded by double underscores (__), we never call __str__ directly.Β  It is there, waiting to "answer the call" when we ask to print an object or use str()to convert an object to a string.)
Question: What output will be produced when the following lines of code are executed?
t2 = Timer()
t2.minutes = 7
t2.seconds = 15
print(t2)
  • 0:7:15
  • 0 7 15
  • Hours: 0 Minutes: 7 Seconds: 15
  • Hours: 15 Minutes: 7 Seconds: 0
  • 15:7:0
  • 15Β  7Β  0

12. Setting Attributes.

Consider the following class definition.
class Timer:
    """ A class that represents a timer. """
    def __init__(self):
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def set_hours(self, h):
        self.hours = h

    def set_minutes(self, m):
        self.minutes = m

    def set_seconds(self, s):
        self.seconds = s

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
What output will be produced when the following lines of code are executed?
t1 = Timer()
t1.set_hours(7)
print(t1)
  • 7:0:0
  • 7 0 0
  • 0:0:7
  • 0 0 7

13. Calling Methods 2.

Consider the following class definition.
class Timer:
    """ A class that represents a timer. """
    def __init__(self):
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def set_hours(self, h):
        self.hours = h

    def set_minutes(self, m):
        self.minutes = m

    def set_seconds(self, s):
        self.seconds = s

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
What output will be produced when the following lines of code are executed?
t2 = Timer()
t2.set_hours(14)
t2.set_minutes(55)
t2.set_minutes(27)
t2.print_with_labels()
  • 14:27:0
  • 14:55:27
  • Hours: 14 Minutes: 27 Seconds: 0
  • Hours: 14 Minutes: 55 Seconds: 27
  • Hours: 15 Minutes: 22 Seconds: 0
  • 15:22:0

14. Writing Methods.

Consider the following class definition.
class Timer:
    """ A class that represents a timer. """
    def __init__(self):
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
Which of the following is the correct definition for a new Timer class method called set that will take three integer values representing hours, minutes, and seconds and set the object’s instance variables (attributes) appropriately?
  • def set(self, h, m, s):
        self.hours = h
        self.minutes = m
        self.seconds = s
    
  • def set(h, m, s):
        self.hours = h
        self.minutes = m
        self.seconds = s
    
  • Remember, when writing a method for a class, you always need to include self as the first parameter.
  • def set(self):
        self.hours = h
        self.minutes = m
        self.seconds = s
    
  • To be able give new values to the object’s hours and minutes, you give the method parameters to hold those values.
  • def set(self, h, m, s):
        hours = h
        minutes = m
        seconds = s
    
  • You need to assign the new values to the object’s attributes.

15. Calling the Set Method.

16. Convert to Seconds.

Implement a method for the Timer class, convert_to_seconds. For a given Timer, the method returns the equivalent number of seconds. For example, if Timer t1 is currently set to 0:1:15 (0 hours, 1 minute, 15 seconds), then the call t1.convert_to_seconds() will return 75.
Hint: Remember that inside the body of the convert_to_seconds method definition, we use the parameter selfto refer to the Timerobject which activated the method.
The Timer class definition is given below for reference.
class Timer:
    """ A class that represents a timer. """
    def __init__(self, h, m, s):
        self.hours = h
        self.minutes = m
        self.seconds = s

    def print_with_labels(self):
        print('Hours:', self.hours, end=' ')
        print('Minutes:', self.minutes, end=' ')
        print('Seconds:', self.seconds)

    def __str__(self):
        return f'{self.hours}:{self.minutes}:{self.seconds}'
For example:
Test Result
timer1 = Timer(0, 5, 30)
timer1.convert_to_seconds()
330

17. Add Two Timers.

Write a function, add_timers, that takes two Timer objects, t1 and t2, and returns a new Timer object that is the sum of t1 and t2. Neither of the original Timer objects should be changed.
The minutes and seconds attributes for the new Timer object must be valid (i.e., in the range 0 through 59). This means you may need to do some conversion from seconds to minutes and from minutes to hours. You may assume that the attributes for the provided Timer objects t1 and t2 are valid.
Note that the function you are writing is NOT a Timer class method. It is just a regular function.
HINT: Use floor division (//) and remainder (%) to implement this function.
The Timer class is given below for reference.
class Timer:
        """ A class that represents a timer. """
        def __init__(self, h, m, s):
            self.hours = h
            self.minutes = m
            self.seconds = s

        def print_with_labels(self):
            print('Hours:', self.hours, end=' ')
            print('Minutes:', self.minutes, end=' ')
            print('Seconds:', self.seconds)

        def get_seconds(self):
            return self.seconds

        def get_minutes(self):
            return self.minutes

        def get_hours(self):
            return self.hours

        def __str__(self):
            return f'{self.hours}:{self.minutes}:{self.seconds}'
For example:
Test Result
timer1 = Timer(0, 5, 30)
timer2 = Timer(2, 19, 0)
add_timers(timer1, timer2)
2:24:30
timer1 = Timer(1, 51, 41)
timer2 = Timer(4, 48, 59)
add_timers(timer1, timer2)
6:40:40

18. Implementing the Comparison Operators.

    Python has "magic" methods to make the comparison operators work with objects. The six comparison operators (<, <=, >, >=, == and !=) are enabled simply by implementing the following special methods: __lt__, __le__, __gt__, __ge__, __eq__ and __ne__
    For example, here is the code to implement __lt__ (i.e., <, theΒ "less than" operator) for the Timerclass. Notice we start by converting both Timers to an integer number of seconds, then simply compare those numbers of seconds. Comparing two Timers reduces to the problem of comparing two integers.
    def __lt__(self, other):
        sec_self = self.convert_to_seconds()
        sec_other = other.convert_to_seconds()
        return sec_self < sec_other
    
    Did you follow the link to read about comparison operators?
  • True.

  • False.

19. Equivalence and Inequivalence Operators: ==, !=.

Two Timer objects are equivalentexactly when they represent the same amount of time.Β Implement the __eq__method (i.e.,Β ==Β ) for the Timerclass.
Hint: You should assume that the convert_to_seconds method has already been implemented.
For example:
Test Result
Timer(0, 5, 30) == Timer(0, 5, 30)
True
Timer(0, 5, 30) != Timer(0, 5, 30)
False
Timer(1, 5, 30) == Timer(0, 5, 30)
False
Timer(1, 5, 30) != Timer(0, 5, 30)
True
You have attempted of activities on this page.