CodeStart / Python Course / Lesson 16
Lesson 16: Class Exercises
Let's practice writing your first basic classes and objects! Try to solve these starter exercises on your own before opening the answers.
1st Exercise: The Dog Class
Create a class named Dog. It should have a constructor (__init__) that takes name and breed as parameters. Then, add a method called bark(self) that prints: "[name] says Woof!"
Reveal Answer
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says Woof!")
my_dog = Dog("Rex", "German Shepherd")
my_dog.bark()Output
Rex says Woof!2nd Exercise: Rectangle Area Calculator
Create a class named Rectangle that takes width and height in its constructor (__init__). Add a method called calculate_area(self) that returns the area of the rectangle (width * height).
Reveal Answer
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def calculate_area(self):
return self.width * self.height
rect = Rectangle(5, 10)
print(rect.calculate_area())Output
50Want XP, levels and progress tracking? Play this lesson in the CodeStart game.
Play Lesson 16