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

my_pet = Pet("Peter")
print(my_pet.name)

In your Notebook

Respond to the following

  1. What is the purpose of the __init__ method?
  2. What if you wanted to initialize all pet objects with a name and a color?
  3. How would you modify the code to create a pet object with a name of “Peter” and a color of “brown”?

Lab

In this lab, we will create a Pet class that will keep track of the type of animal, color, food, noise and name of a given animal.

Create a class called Pet that has the following attributes

Specifications

  1. Make sure to use the __init__ method to create these attributes.
  2. Create a list of pets.
  3. Create a function that takes in a list of pets and prints out the name and the food attributes.
  4. Test your function with your list of pets.

Check your understanding

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

1. What is the purpose of the __init__ method?

  • It prints the object
  • It sets up a new instance, usually by giving it starting attributes
  • It deletes an object when finished
  • It converts an object to a string

Python calls __init__ automatically when you create an instance, so it is the place to initialize attributes.

2. In def __init__(self, name):, what does self refer to?

  • The class itself
  • The name that was passed in
  • The Python interpreter
  • The particular instance being created or used

self lets the method reach the attributes of the specific object it was called on.

3. Given __init__(self, name, color), which call correctly creates a pet?

  • Pet("Peter", "brown")
  • Pet(self, "Peter", "brown")
  • Pet()
  • Pet.__init__

Python supplies self automatically, so you pass only the remaining arguments when instantiating.

Downloads