Python Intermediate - Lesson 16 - Classes and Objects
Python Intermediate · Lesson 16
Classes and Objects
A class groups related data and behavior into a new kind of object. You already use objects in Python: strings, lists, and dictionaries all have methods. In this lesson, you’ll define a small class of your own and create multiple independent objects from it.
self, create instances, and keep related data and behavior
together.
1. Define a class
A class is a recipe for creating objects. By convention, class names use
CapWords. The __init__ method runs when a new
instance is created.
class StudySession:
def __init__(self, topic, minutes):
self.topic = topic
self.minutes = minutes
session = StudySession("Python basics", 25)
print(session.topic)
print(session.minutes)
self refers to the particular instance being initialized.
Assignments such as self.topic = topic store values on that
object so its methods can use them later.
2. Add an instance method
A method is a function defined inside a class. Its first parameter is
conventionally named self, allowing it to read or update that
instance's attributes.
class StudySession:
def __init__(self, topic, minutes):
self.topic = topic
self.minutes = minutes
def summary(self):
return f"{self.topic}: {self.minutes} minutes"
session = StudySession("Python basics", 25)
print(session.summary())
Call an instance method with dot notation:
session.summary(). Python passes the instance as
self automatically.
3. Create multiple independent objects
Each call to the class creates a separate object with its own attributes. Put objects in a list when you want to process a group of them.
sessions = [
StudySession("Functions", 30),
StudySession("SQLite", 25),
StudySession("Web APIs", 40),
]
for session in sessions:
print(session.summary())
total_minutes = sum(session.minutes for session in sessions)
print(f"Total: {total_minutes} minutes")
The objects share the same class definition, but changing one instance's attributes does not automatically change another object's attributes.
4. Validate data when objects are created
A class can check its inputs in __init__, so every instance
begins in a valid state. This example rejects a blank topic and non-positive
or non-integer minutes.
class StudySession:
def __init__(self, topic, minutes):
if not isinstance(topic, str):
raise TypeError("topic must be text")
clean_topic = " ".join(topic.split())
if not clean_topic:
raise ValueError("topic cannot be blank")
if not isinstance(minutes, int) or isinstance(minutes, bool):
raise TypeError("minutes must be an integer")
if minutes <= 0:
raise ValueError("minutes must be greater than zero")
self.topic = clean_topic
self.minutes = minutes
After validation, other methods can rely on the attributes meeting those
rules. Rejecting bool explicitly matters because in Python
bool is a subclass of int.
Hands-on exercises
-
Define a
Bookclass that stores a title and page count. Create two books and print each title. -
Add a
describe()method toBookthat returns a sentence with its title and page count. Call the method on both objects.
Show Solution & Common Mistakes
Exercise 1 — one possible solution
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
first_book = Book("The Small Observatory", 180)
second_book = Book("Maps for Tomorrow", 240)
print(first_book.title)
print(second_book.title)
Exercise 2 — one possible solution
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def describe(self):
return f"{self.title} has {self.pages} pages."
first_book = Book("The Small Observatory", 180)
second_book = Book("Maps for Tomorrow", 240)
print(first_book.describe())
print(second_book.describe())
Common mistakes:
-
Forgetting
selfas the first parameter of an instance method. -
Writing
topic = topicinstead of assigning an instance attribute withself.topic = topic. -
Calling a method without parentheses, such as
session.summary, when you intend to run it. - Indenting the method outside the class body.
- Creating a class for a task that would be clearer as a simple function.
Quick quiz
Choose an answer, then select Check answer.
1. What is __init__ commonly used for?
2. In an instance method, what does self refer to?
3. What happens when you create two instances of one class?
Mini-project: Study Session Tracker
Build a small program that represents study sessions as objects and keeps them in a tracker. Each session should validate its own data and know how to produce a readable summary.
Requirements:
- Create a
StudySessionclass withtopicandminutesattributes. - Reject blank topics, non-integer minutes, and zero or negative minutes.
- Add a
summary()method for a session. - Create a
StudyTrackerclass that stores sessions. - Display each session and calculate the overall total.
Hints: store the collection on self.sessions.
Use sum() with a generator expression to total the
minutes attributes.
Show Full Project Solution
class StudySession:
def __init__(self, topic, minutes):
if not isinstance(topic, str):
raise TypeError("topic must be text")
clean_topic = " ".join(topic.split())
if not clean_topic:
raise ValueError("topic cannot be blank")
if not isinstance(minutes, int) or isinstance(minutes, bool):
raise TypeError("minutes must be an integer")
if minutes <= 0:
raise ValueError("minutes must be greater than zero")
self.topic = clean_topic
self.minutes = minutes
def summary(self):
return f"{self.topic}: {self.minutes} minutes"
class StudyTracker:
def __init__(self):
self.sessions = []
def add_session(self, session):
if not isinstance(session, StudySession):
raise TypeError("session must be a StudySession")
self.sessions.append(session)
def total_minutes(self):
return sum(session.minutes for session in self.sessions)
def summaries(self):
return [session.summary() for session in self.sessions]
def main():
tracker = StudyTracker()
tracker.add_session(StudySession("Functions", 25))
tracker.add_session(StudySession("SQLite practice", 35))
tracker.add_session(StudySession("Web APIs", 20))
print("Study sessions")
for line in tracker.summaries():
print(f"- {line}")
print(f"Total: {tracker.total_minutes()} minutes")
if __name__ == "__main__":
main()
Run the file to see three sessions and their 80-minute total. Try adding
another StudySession, or create an empty
StudyTracker and check that its total is zero.