Object-Oriented Programming Basics
A class is a blueprint for creating objects that bundle data (attributes) and behavior (methods) together. Instead of passing a dictionary around between separate functions, you can define a Course class that knows both its own data and what it’s able to do.
class Course:
def __init__(self, title, lessons):
self.title = title
self.lessons = lessons
def lesson_count(self):
return len(self.lessons)
python_course = Course("Python", ["Intro", "Variables", "Loops"])
print(python_course.lesson_count()) # 3
Key concepts
- __init__ runs automatically when a new object is created, setting up its starting attributes
- self refers to the specific object the method is being called on — it’s always the first parameter of a method, though Python passes it automatically, so you never write it yourself when calling the method
- Methods are simply functions defined inside a class
Multiple objects, independent state
python_course = Course("Python", ["Intro", "Variables"])
js_course = Course("JavaScript", ["Intro", "DOM", "Async"])
print(python_course.lesson_count()) # 2
print(js_course.lesson_count()) # 3
Each object created from a class has its own independent copy of the attributes defined in __init__ — changing js_course.title has no effect whatsoever on python_course, even though they were built from the exact same blueprint.
Inheritance
class CertifiedCourse(Course):
def __init__(self, title, lessons, certificate_name):
super().__init__(title, lessons)
self.certificate_name = certificate_name
CertifiedCourse gets everything Course already has — the title attribute, the lessons attribute, and the lesson_count() method — plus a new certificate_name attribute of its own. super().__init__(...) calls the parent class’s constructor, so you don’t have to repeat that setup logic. This is how you avoid rewriting shared behavior every time you need a more specialized version of something.
When to reach for a class
Not everything needs to be a class — a simple function is often enough. Reach for a class when you have data and behavior that clearly belong together and when you expect to create more than one instance of that “thing” (multiple courses, multiple students, multiple orders). If you only ever need one of something, a plain dictionary or a set of functions is usually simpler.