2nd Semester Intro to Computer Science

What you will learn

Reading

Do Now

In your Console

Type the following

class Time(object):
  def __init__(self, hour, minute, second):
        self.hour = hour
        self.minute = minute
        self.second = second

time1 = Time(5, 32, 0)
time2 = Time(23, 11, 11)

print(time1)
print(time2)

In your Notebook

Respond to the following

  1. Based on what is output, how can you tell the difference between time1 and time2?
  2. What happens if you try to add time1 add time2?

Lab

Instructions

Tips to give students

Extra Credit

Return to your Pet class from Lab 7.02. Research the isinstance function to write a method, is_friend that will take in another pet and return True if the two pets are friends, and false if they are not.

Rules

Check your understanding

Pick an answer for each question. You can try again until you get it right.

1. What does print(time1) show by default if the class has no __str__ method?

  • The hour, minute, and second values
  • An error message
  • A generic description of the object, such as its class and memory location
  • Nothing

Without __str__, Python cannot know how to describe your object nicely, so it prints a generic default.

2. What does defining __add__ in a class let you do?

  • Add new attributes to every instance
  • Use the + operator on instances of that class
  • Make the class inherit from another
  • Add methods after the class is created

This is operator overloading: a + b calls a.__add__(b).

3. How is a method different from an ordinary function?

  • A method cannot take arguments
  • A method always returns a string
  • A method can only be called once
  • A method is defined inside a class and is called on an instance, which is passed as self

Methods belong to a class and automatically receive the instance they are called on.

Downloads