Exercise 1: Introduction to Objects and Classes
Welcome to Python 2, Lesson 5! Today, we'll learn about objects and classes, fundamental concepts in object-oriented programming (OOP).
What are Objects and Classes?
A class is like a blueprint for creating objects. An object is an instance of a class, which contains its own data and behaviors.
Let's start with a simple example of a class:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
# Create a Dog object
my_dog = Dog("Buddy", 3)
print(f"{my_dog.name} is {my_dog.age} years old.")
print(my_dog.bark())Now it's your turn! Create a class called Cat with the following:
- An
__init__method that takesnameandcoloras parameters - A method called
meowthat returns a string like "name says Meow!" - Create a Cat object and call its meow method
# Define your Cat class here
# Create a Cat object and call its meow method