🔄 Quick Recap (Day 10)

  • You mastered dictionaries for key:value storage.

  • You created, accessed, modified, and removed dictionary entries.

🎯 What You’ll Learn Today

  1. What classes and objects are in Python.

  2. How to define a simple class with attributes.

  3. How to create instances (objects) of your class.

  4. How to add methods (functions) to classes.

📖 Overview: Classes and Objects

Think of a class as a blueprint (like a recipe) and an object as the baked dish (the result). Classes define attributes (data) and methods (actions) that their objects will have.

class Dog:
    def __init__(self, name, age):
        self.name = name      # attribute
        self.age = age        # attribute

    def bark(self):
        print(f"{self.name} says woof!")  # method
  • class Dog: starts the class definition.

  • __init__ is a special method called when creating an object.

  • self refers to the specific object instance.

📖 Creating Objects and Using Methods

Instantiation

Create an object by calling the class:

my_dog = Dog("Buddy", 3)

Accessing Attributes and Calling Methods

print(my_dog.name)  # Buddy
print(my_dog.age)   # 3
my_dog.bark()       # Buddy says woof!

🧙‍♂️ Take the Wand and Try Yourself

  1. Create a file named animal.py.

  2. Define a class Animal with:

    • An __init__ method accepting species and sound.

    • A method make_sound() that prints: "A [species] goes [sound]!".

  3. Instantiate two different animals (e.g., cat, dog) and call make_sound() on each.

Solution Example (animal.py):

# animal.py
class Animal:
    def __init__(self, species, sound):
        self.species = species
        self.sound = sound

    def make_sound(self):
        print(f"A {self.species} goes {self.sound}!")

# Create instances
cat = Animal("cat", "meow")
dog = Animal("dog", "woof")

# Use methods
cat.make_sound()  # A cat goes meow!
dog.make_sound()  # A dog goes woof!

Expected output:

A cat goes meow!
A dog goes woof!

Run:

python animal.py

Once your script prints the correct sounds, you’ve mastered basic classes and objects!

Ready for Day 12: Inheritance & Polymorphism? See you there!

Keep Reading