Lesson 1 of 15 · Classes and Objects
Why Objects?
Understand why object-oriented programming exists, what classes and objects are, and how you have already been using objects in Python, explained in plain English.
- 9 min read
- Intermediate
- Reviewed
- The problem that object-oriented programming solves
- What a class and an object are, using everyday examples
- Why you have already been using objects all along
- The four words you will use throughout this course
A program that is starting to hurt
Imagine you are building a small app for a school. Every student has a name, an age and a list of marks. With what you know so far, you might store each student as a dictionary and write functions that work on them:
student_1 = {"name": "Ada", "age": 17, "marks": [92, 88, 95]}
student_2 = {"name": "Alan", "age": 16, "marks": [71, 64, 80]}
def average(student):
return sum(student["marks"]) / len(student["marks"])
def add_mark(student, mark):
student["marks"].append(mark)
add_mark(student_2, 90)
print(student_1["name"], round(average(student_1), 1))
print(student_2["name"], round(average(student_2), 1))This works. But think about what happens as the app grows:
- The data and the functions are separate. Nothing says
average()belongs with students. A new teammate has to hunt for the functions that work on a student. - Nothing protects the data. Someone can type
student_1["mrks"]by mistake, or setstudent_1["age"] = -5, and Python will not complain. - Every student must be built by hand, with exactly the right keys, every single time.
With three students, this is fine. With courses, teachers, timetables and exams, each needing their own data and their own functions, it becomes a tangle.
The idea: keep the data and the actions together
In simple words: instead of keeping data in one place and functions somewhere else, you build "things" that carry both. An object bundles together:
- data about something, such as a student's name and marks
- actions that make sense for that thing, such as "add a mark" or "work out the average"
Here is the same program written with a class. Do not worry about the details yet. You will learn every part of it in the next lessons. For now, just compare how it reads.
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
self.marks = []
def add_mark(self, mark):
self.marks.append(mark)
def average(self):
return sum(self.marks) / len(self.marks)
ada = Student("Ada", 17)
ada.add_mark(92)
ada.add_mark(88)
print(ada.name, ada.average())Everything about a student now lives in one place: the Student class. To use it, you create a student, then ask that student to do things: ada.add_mark(92), ada.average(). The code reads almost like a sentence.
Classes and objects, in everyday terms
The two most important words in OOP are class and object.
Some everyday comparisons:
| Class (the blueprint) | Objects (things built from it) |
|---|---|
| A cookie cutter | The cookies you cut out |
| An architect's house plan | The houses built from that plan |
| A blank form | Each filled-in copy of the form |
Student | Ada, Alan, Grace |
Two houses built from the same plan have the same layout, but each has its own colour, furniture and family. In the same way, every Student object has a name and marks, but Ada's marks are not Alan's marks.
You have been using objects all along
Here is a secret: everything in Python is already an object. Every string, number, list and dictionary you have ever made was an object built from a class.
greeting = "hello world" numbers = [3, 1, 2] print(type(greeting)) print(type(numbers)) print(type(42))
str, list and int are classes. "hello world" is an object of the class str.
And the dot you have been typing all along is how you use an object's actions:
greeting = "hello world"
numbers = [3, 1, 2]
print(greeting.upper())
print(greeting.count("o"))
numbers.append(5)
numbers.sort()
print(numbers)upper(), count(), append() and sort() are actions that belong to strings and lists. Each one works on its own object: sorting numbers does not sort any other list. In this course you will learn to create your own classes, so your own things can work the same way.
Two more words: attribute and method
A simple way to remember: attributes are what an object has, and methods are what it can do.
Quick recap of the words
| Word | Meaning | Example |
|---|---|---|
| Class | A blueprint for a kind of thing | Student |
| Object or instance | One thing made from a class | ada |
| Attribute | A piece of data stored on an object | ada.name, ada.marks |
| Method | A function that belongs to a class | ada.add_mark(92) |
Do you always need classes?
No. A short script that reads a file and prints a total does not need any classes, and adding them would only make it longer. OOP shines when you have several kinds of things, each with their own data and behaviour, such as students, courses and teachers, or users, messages and conversations.
A good habit: start simple. When you notice you are passing the same group of data into many functions, that group probably wants to be a class.
Common mistakes
Show which class each of these everyday values was built from.
values = [42, "AI", [1, 2, 3], {"level": "beginner"}]
# Every value in Python is an object made from a class.
# Print the name of each value's class, one per line.
# Tip: type(value).__name__ gives the class name as text.
# Output must be exactly:
# int
# str
# list
# dict
What is the relationship between a class and an object?
Summary
- OOP organises code around objects that keep related data and actions together.
- A class is a blueprint, and an object (or instance) is one thing built from it.
- Attributes are an object's data, and methods are its actions.
- Every value in Python is already an object, which is why you can write
"text".upper(). - Use classes when you have several kinds of things with their own data and behaviour.
Next: writing your very first class.
Finished reading? Tick it off to track your progress.