2nd Semester Intro to Computer Science

What you will learn

Reading

Do Now

In your Console

Type the following


class Pet(object):
  def __init__(self, name):
  self.name = name
  def make_noise(self):
  print("Noise!")
  return

class Dog(Pet)

# A specific type of Pet!

dog1 = Dog()
dog1.make_noise()

In your Notebook

Respond to the following

  1. What is the output when you run this code?
  2. Rewrite the code to resolve the error and make this work properly
  3. What happens when you call method make_noise?

Lab

Overview

Given the following example, practice using inheritance to create specific child classes for different types of Pokemon.

Create the three child classes below

1. Water Type
2. Fire Type
3. Grass Type

Note: In order to check what type an object is you can use isinstance which takes in an object, a class and returns a boolean if the object is the type of the inputted class.

Example Code

my_pet = Pet()
isinstance(my_pet, Pet) # returns true
isinstance(my_pet, Dog) # returns false

Check your understanding

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

1. In class Dog(Pet):, which class is the parent?

  • Pet
  • Dog
  • Both of them
  • Neither, Dog is a function

The class in parentheses is the parent, and Dog is the child that inherits from it.

2. If a child class does not define make_noise but its parent does, what happens when you call make_noise on a child instance?

  • An error, because the method is missing
  • Nothing happens
  • It runs the parent’s version
  • Python asks you to define it

A child inherits all methods of its parent unless it overrides them.

3. What does it mean to override a method in a child class?

  • Delete the method from the parent class
  • Define a method with the same name in the child so its version is used for child instances
  • Call the method twice
  • Copy the parent class into a new file

The child's own definition takes priority over the parent's for instances of the child.

Downloads