Unit 6 • Lesson 2

Defining and Creating Classes

Overview

Classes act as blueprints for creating new objects. You'll learn how to define classes with the class keyword, add attributes, and use the __init__ method to initialize object data, giving you the foundation to create your own custom objects.

Beginner 25–30 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • Class syntax: Learn how to define a class using the class keyword.
  • __init__ method: Understand how to initialize objects with the __init__ method.
  • Attributes: Learn how to add attributes to classes.
  • Class structure: Understand the basic structure of a Python class.

Why This Matters

Classes are the foundation of OOP in Python. Once you know how to define a class, you can create your own custom objects that model real-world things. The __init__ method is special - it runs automatically when you create a new object, letting you set up the object's initial state. This is your first step into real object-oriented programming!

Step 1: Basic Class Definition

You define a class using the class keyword followed by the class name:

Simple Class Definition
class Person:
    pass

# This creates an empty class
# 'pass' means "do nothing" - it's a placeholder
1

Class Keyword

Use class followed by the class name. Class names should start with a capital letter (PascalCase).

2

Colon

End the class definition line with a colon :. Everything indented below belongs to the class.

3

Class Body

The class body contains methods and attributes. For now, we use pass as a placeholder.

Key Concept: A class definition is like declaring "I'm going to create a blueprint for this type of object." The class itself doesn't create any objects - it just defines what objects of this type will look like!

Mini Practice #1: Define a Simple Class

Try It Yourself

Create a simple class:

Press Run to see output

What happened? You created a Dog class! Right now it's empty (just has pass), but you've defined the blueprint. In the next steps, we'll add attributes and methods to make it useful!

Step 2: The __init__ Method

The __init__ method is a special method that runs automatically when you create a new object. It's used to initialize the object's attributes:

Using __init__
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# When you create a Person object, __init__ runs automatically
# It sets up the object's initial attributes
1

Special Method

__init__ is a special method (notice the double underscores). It's called automatically when you create a new object.

2

Self Parameter

The first parameter is always self. It refers to the object being created. You don't pass it when creating objects!

3

Initialize Attributes

Use self.attribute_name = value to set attributes. These become part of the object.

Understanding self

self is a reference to the object itself. When you write self.name = name, you're saying "set this object's name attribute to the name value passed in." Every method in a class needs self as the first parameter!

Mini Practice #2: Using __init__

Try It Yourself

Create a class with __init__:

Press Run to see output

What happened? When you created book1 = Book("Python Basics", "John Doe"), Python automatically called the __init__ method. It set self.title = "Python Basics" and self.author = "John Doe". Now the book object has those attributes!

Step 3: Adding Attributes

Attributes are variables that belong to an object. You can set them in __init__ or add them later:

Class Attributes
class Car:
    def __init__(self, brand, color):
        self.brand = brand      # Instance attribute
        self.color = color      # Instance attribute
        self.speed = 0          # Default value

# Each Car object will have its own brand, color, and speed
1

Instance Attributes

Attributes defined with self. are instance attributes. Each object has its own copy of these attributes.

2

Default Values

You can set default values for attributes. Here, self.speed = 0 gives every car a starting speed of 0.

3

Access Attributes

After creating an object, access attributes using dot notation: car.brand, car.color.

Step 4: Class Structure

A complete class typically has:

Complete Class Example
class Student:
    def __init__(self, name, student_id):
        # Initialize attributes
        self.name = name
        self.student_id = student_id
        self.grades = []
    
    def add_grade(self, grade):
        # Method to add a grade
        self.grades.append(grade)
    
    def get_average(self):
        # Method to calculate average
        if self.grades:
            return sum(self.grades) / len(self.grades)
        return 0

Class Components

  • __init__ method: Initializes the object with starting values
  • Attributes: Data stored in the object (name, student_id, grades)
  • Methods: Functions that belong to the class (add_grade, get_average)

End-of-Lesson Exercises

Exercise 1: Create a Simple Class

Create a Dog class with an __init__ method that takes name and breed as parameters. Set these as attributes. Then create a Dog object with name "Buddy" and breed "Golden Retriever", and print the dog's name and breed.

Define class Dog, add __init__ with self, name, breed, then create an object.

Write your code above and click "Check Answer" to verify it's correct.

Exercise 2: Class with Default Value

Create a Circle class with an __init__ method that takes radius as a parameter. Also add a default attribute color set to "Red". Create a Circle object with radius 5, then print the radius and color.

Define class Circle, add __init__ with self and radius, set self.color = "Red", create object, print attributes.

Write your code above and click "Check Answer" to verify it's correct.