11

Day 11: Classes and Objects

Chapter 11 • Intermediate

45 min

Classes and objects are the foundation of Object-Oriented Programming (OOP) in Python. They help you organize code and create reusable components.

What are Classes?

A class is like a blueprint or template for creating objects. Think of it as a cookie cutter that creates cookies (objects) with the same shape.

What are Objects?

An object is an instance of a class. It's like a specific cookie made from the cookie cutter. Each object has its own data and can perform actions.

Classes and Objects

  • Class - Blueprint for creating objects
  • Object - Instance of a class
  • Attributes - Variables that belong to a class
  • Methods - Functions that belong to a class
  • Constructor - Special method that runs when creating an object
  • Inheritance - Creating new classes based on existing ones

Benefits of Classes:

  • Code Reusability - Write once, use many times
  • Organization - Group related data and functions
  • Encapsulation - Hide internal details
  • Inheritance - Build upon existing classes

Hands-on Examples

Basic Class Example

# Define a class
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def bark(self):
        return f"{self.name} says Woof!"
    
    def get_info(self):
        return f"{self.name} is {self.age} years old"

# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# Use the objects
print(dog1.bark())
print(dog2.get_info())
print(f"Dog1 name: {dog1.name}")
print(f"Dog2 age: {dog2.age}")

This example shows how to create a class with attributes (name, age) and methods (bark, get_info). We create two dog objects and use their methods.