🔄 Quick Recap (Day 10)
You mastered dictionaries for key:value storage.
You created, accessed, modified, and removed dictionary entries.
🎯 What You’ll Learn Today
What classes and objects are in Python.
How to define a simple class with attributes.
How to create instances (objects) of your class.
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!") # methodclass Dog:starts the class definition.__init__is a special method called when creating an object.selfrefers 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
Create a file named
animal.py.Define a class
Animalwith:An
__init__method acceptingspeciesandsound.A method
make_sound()that prints:"A [species] goes [sound]!".
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.pyOnce your script prints the correct sounds, you’ve mastered basic classes and objects!
Ready for Day 12: Inheritance & Polymorphism? See you there!