What you will learn
- Define and identify: self,
__init__ - Create a class with an init method
- Understand and use the
selfargument - Instantiate a class with arguments
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
- What is the purpose of the
__init__method? - What if you wanted to initialize all pet objects with a name and a color?
- 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
- Animal (i.e. dog, cat, fish)
- Color (i.e. spotted, black, tabby, white)
- Food (i.e. kibbles, tuna, fish flakes)
- Noise (i.e. meow, woof, bark)
- Name (i.e. Sparky, Scooby Doo)
Specifications
- Make sure to use the
__init__method to create these attributes. - Create a list of pets.
- Create a function that takes in a list of pets and prints out the name and the food attributes.
- 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.