Object-Oriented Basics

object-oriented-python
Define classes, create objects, store attributes, write methods, and use self.
  • Level: Intermediate
  • Estimated time: 35–50 minutes
  • You will learn: Define classes, create objects, store attributes, write methods, and use self.
  • Practice in: VS Code, Jupyter, or Colab

Questions

  • What problem does Object-Oriented Basics help us solve in a small Python program?
  • What should we predict before running the example?
  • What value, output, or error should we inspect after changing one line?

Objectives

  • Run a complete example for object-oriented basics in Colab.
  • Explain the example line by line using plain language.
  • Change one part of the code and predict the result before running it.
  • Recognize one common mistake and use the error message as evidence.

Hands-on episode: Object-Oriented Basics

A class defines attributes and methods. An object stores its own attribute values, and methods use self to access the object they are working on.

We will learn this by running code, not by memorizing a definition first. Open the Colab notebook from the button above, find this section, and run each cell in order. Keep a small note beside the notebook with three columns: prediction, actual result, and what changed.

Example 1.1

Predict how each method changes the individual counter object.

class Counter:
def __init__(self):
self.value = 0

def increment(self):
self.value = self.value + 1

counter = Counter()
counter.increment()
print(counter.value)

Run the cell once without editing it. If the result is different from your prediction, leave the prediction visible and write one sentence about the difference. That sentence is more useful than a perfect first guess.

Explain Example 1.1

  • class Counter defines a blueprint for counter objects.
  • __init__ runs when a new counter is created and gives it a starting value.
  • self.value belongs to this particular counter object.
  • counter.increment() calls the method with counter as self, so that object’s value changes.

Now explain the example out loud or in a Markdown cell. Use short sentences: “this line creates…”, “this name stores…”, “this output appears because…”. If you cannot explain a line yet, run only the lines above it and inspect the values that exist at that moment.

Challenge 1.1

NoteChallenge

Create other = Counter() and print both values after incrementing only counter. Each object has its own attribute value, which is the point of making instances.

Show a safe way to approach the challenge
  1. Copy Example 1.1 into a new Colab cell.
  2. Change exactly one value, name, condition, or line.
  3. Write the expected output before running the cell.
  4. Run the cell and compare the actual result with your prediction.
  5. If the result surprises you, undo the change and try a smaller one.

Suggested first move: Create other = Counter() and print both values after incrementing only counter.

Debugging checkpoint 1.1

WarningDebugging checkpoint

Forgetting self is common. If a method needs to read or change the object’s data, use self.attribute. Also do not make a class just because classes exist; functions and dictionaries are often clearer for small tasks.

Do not debug by rewriting the whole example. Read the error type or surprising output, inspect the closest value with print(...) or type(...), then change one thing. This is the same routine you will use in larger projects.

Apply it

Create a Student class with name and score, then add a method that increases the score. Make two students and show that changing one does not change the other.

Finish by adding a Markdown cell that answers: What did this example teach me that I can reuse in a project?

Key points

  • Learn the concept by running a complete, small example first.
  • Predict before execution so your thinking becomes visible.
  • Change one thing at a time so cause and effect stay clear.
  • Treat errors as clues about the exact line or value Python could not handle.

Why this matters

Define classes, create objects, store attributes, write methods, and use self.

This lesson combines related subtopics that belong together in one learning conversation. You will still pause for a quiz after each section, but you do not need to jump between separate pages while building one clear explanation.

NoteGuiding questions

By the end of this lesson, you should be able to answer:

  • How do the sections in Object-Oriented Basics fit together?
  • Which small example demonstrates each section?
  • Which debugging clue should I check first for each section?
NoteLearning objectives

You will practice how to:

  • explain the shared concept for this lesson;
  • use each section as one step in a larger workflow;
  • complete 3 short section quizzes before moving on;
  • connect examples, mistakes, and debugging routines.

Lesson map

  • 1. Classes and Objects — Define a new kind of object and create instances from it.
  • 2. Attributes and Methods — Store object data in attributes and object behavior in methods.
  • 3. init and self — Initialize each object with its own starting data.

Classes, objects, and attributes

A class describes a kind of object. Each object has its own attributes, and methods use self to work with that particular object.

flowchart LR
  class["class Student<br/>blueprint"] --> ada["object<br/>ada"]
  class --> grace["object<br/>grace"]
  ada --> ada_name["attribute<br/>name = 'Ada'"]
  grace --> grace_name["attribute<br/>name = 'Grace'"]
  ada --> method["method call<br/>ada.study()"]
  method --> self["self refers to<br/>ada"]

If self feels mysterious, read it as “this specific object.”

1. Classes and Objects

Define a new kind of object and create instances from it.

TipAnalogy

A class is a cookie cutter, and objects are the individual cookies.

What this means

A class is a blueprint; an object is one concrete instance built from that blueprint.

Example 1

Predict what will happen before you run the code.

class Dog:
    pass

fido = Dog()
print(type(fido))

Step-by-step explanation

  1. class Dog: — pause here and say what this line reads, creates, changes, or displays.
  2. pass — pause here and say what this line reads, creates, changes, or displays.
  3. fido = Dog() — pause here and say what this line reads, creates, changes, or displays.
  4. print(type(fido)) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

A class describes many possible objects; an instance is one actual object.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

2. Attributes and Methods

Store object data in attributes and object behavior in methods.

TipAnalogy

Attributes are facts on an ID card; methods are actions the person can perform.

What this means

Attributes describe what an object knows; methods describe what it can do.

Example 2

Predict what will happen before you run the code.

class Counter:
    value = 0

    def show(self):
        print(self.value)

counter = Counter()
counter.show()

Step-by-step explanation

  1. class Counter: — pause here and say what this line reads, creates, changes, or displays.
  2. value = 0 — pause here and say what this line reads, creates, changes, or displays.
  3. def show(self): — pause here and say what this line reads, creates, changes, or displays.
  4. print(self.value) — pause here and say what this line reads, creates, changes, or displays.
  5. counter = Counter() — pause here and say what this line reads, creates, changes, or displays.
  6. Continue the same process for the remaining lines, one line at a time.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

A method needs self as its first parameter so it can work with the specific object.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

3. init and self

Initialize each object with its own starting data.

TipAnalogy

init is the sign-up form each new club member fills out; self is the individual member’s record.

What this means

init runs when a new object is created; self refers to that object.

Example 3

Predict what will happen before you run the code.

class Student:
    def __init__(self, name):
        self.name = name

student = Student("Ada")
print(student.name)

Step-by-step explanation

  1. class Student: — pause here and say what this line reads, creates, changes, or displays.
  2. def __init__(self, name): — pause here and say what this line reads, creates, changes, or displays.
  3. self.name = name — pause here and say what this line reads, creates, changes, or displays.
  4. student = Student("Ada") — pause here and say what this line reads, creates, changes, or displays.
  5. print(student.name) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

Forgetting self.name stores nothing on the object. name alone is just a local variable.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

Notebook and Colab practice

Open a blank notebook at https://colab.new. Use one section at a time: copy the Example 1, predict the result, run it, answer the section quiz, and then move to the next section. This is better than copying the entire page at once.

Instructor note

Teaching notes
  • Treat each section as a short teaching episode.
  • Pause for the section quiz before introducing the next section.
  • Ask learners to compare sections: what stayed the same, and what changed?
  • If time is short, teach the first two sections live and assign the rest as practice.

Key points

TipKey points
  • Classes and Objects: A class is a blueprint; an object is one concrete instance built from that blueprint.
  • Attributes and Methods: Attributes describe what an object knows; methods describe what it can do.
  • init and self: init runs when a new object is created; self refers to that object.
  • Use the section quizzes as gates: review before moving on if a quiz feels uncertain.

References

  • Python classes tutorial: https://docs.python.org/3/tutorial/classes.html
  • dataclasses documentation: https://docs.python.org/3/library/dataclasses.html
  • Python Tutorial: https://docs.python.org/3/tutorial/
  • Quarto OJS documentation: https://quarto.org/docs/interactive/ojs/
  • ipywidgets documentation: https://ipywidgets.readthedocs.io/en/stable/
Back to top