Classes in Python: Build Reusable Blueprints for Objects
Introduction
In this chapter, you will learn Python classes, a core concept of object-oriented programming. Classes help you model real-world entities with both data and behavior. Once you understand classes, your code can be structured in a cleaner, more scalable way.
Prerequisites
- Python
3.10+installed - Basic understanding of variables, functions, dictionaries, and loops
- Ability to run
.pyfiles in terminal or IDE
What Is a Class
A class is a blueprint for creating objects.
Think of it like:
- Class: car design template
- Object: one specific car created from that template
A class usually defines:
- attributes (data)
- methods (actions/behaviors)
1) Define a Simple Class
Use class keyword to define a class.
# Define a simple class
class Student:
pass
# Create object (instance)
stu1 = Student()
print(stu1)pass is used here as a placeholder for empty class body.
2) Constructor __init__
The constructor initializes object data when it is created.
# Define class with constructor
class Student:
def __init__(self, name, age):
# Store object attributes
self.name = name
self.age = age
# Create objects
stu1 = Student("Emma", 10)
stu2 = Student("Liam", 11)
# Print attributes
print(stu1.name, stu1.age)
print(stu2.name, stu2.age)3) Instance Methods
Methods are functions defined inside a class.
# Define class with method
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def introduce(self):
print(f"My name is {self.name}, and my score is {self.score}.")
# Create object and call method
stu = Student("Olivia", 95)
stu.introduce()self refers to the current object instance.
Tip
Best Practice
Use nouns for class names (Student, Book) and verbs for method names (calculate_total, show_profile).
4) Update Object Attributes
Object attributes can be changed after creation.
# Define class
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
# Create object
stu = Student("Noah", 82)
# Update attribute
stu.score = 90
print(stu.score) # 905) Add Helper Methods
You can put business logic directly into class methods.
# Define score analyzer class
class ScoreCard:
def __init__(self, name, chinese, math):
self.name = name
self.chinese = chinese
self.math = math
def average(self):
return (self.chinese + self.math) / 2
def report(self):
print(f"Student: {self.name}")
print(f"Chinese: {self.chinese}")
print(f"Math: {self.math}")
print(f"Average: {self.average():.2f}")
# Use class
card = ScoreCard("Ava", 92, 88)
card.report()6) Real Mini Example: Library Book Class
This example models books in a small library.
# Define Book class
class Book:
def __init__(self, title, author, is_borrowed=False):
self.title = title
self.author = author
self.is_borrowed = is_borrowed
def borrow(self):
if self.is_borrowed:
print(f"'{self.title}' is already borrowed.")
else:
self.is_borrowed = True
print(f"You borrowed '{self.title}'.")
def return_book(self):
if not self.is_borrowed:
print(f"'{self.title}' is already in library.")
else:
self.is_borrowed = False
print(f"You returned '{self.title}'.")
def status(self):
state = "Borrowed" if self.is_borrowed else "Available"
print(f"{self.title} by {self.author} -> {state}")
# Create and use object
book = Book("Python Basics", "Alice Smith")
book.status()
book.borrow()
book.status()
book.return_book()
book.status()This is a realistic object-oriented design pattern.
Warning
Avoid putting unrelated logic into one giant class.
Keep each class focused on one domain responsibility.
Common Beginner Mistakes
Mistake 1: Forgetting self in Method Definition
Instance methods must include self as the first parameter.
Mistake 2: Mixing Class and Object Concepts
Student is a class; stu1 = Student(...) is an object.
Mistake 3: Overusing Classes for Tiny Scripts
For very small one-time scripts, plain functions may be enough.
Surprise Practice Challenge
Build a "Classroom Student Manager" with classes:
- Create
Studentclass withname,chinese,math - Add method
average() - Add method
grade_level()returningA/B/C/D - Create 3 student objects
- Print each student's summary report
If you finish this, you are writing beginner-level OOP code with practical value.
FAQ
Why use classes instead of only functions?
Classes keep related data and behavior together, which improves maintainability for growing projects.
Is object-oriented programming mandatory in Python?
No, but it is very useful for medium and large projects.
What is self exactly?
self is a reference to the current object instance, used to access its attributes and methods.
Can one file have multiple classes?
Yes. It is common, especially when classes are closely related.