Python course Β· Module 3: Object-Oriented Programming
Classes as species in nature
In this lesson9
Welcome to Module 3! Darwin here with a new programming paradigm.
So far you've learned procedural programming - you wrote functions that process data. Now it's time for Object-Oriented Programming (OOP) - a way of organizing code around objects that combine data and behaviors.
Imagine biological classification. Biologists don't describe every animal from scratch. Instead, they create species with shared characteristics:
- All lions (Panthera leo) have four legs, are carnivorous, live in prides
- All ball pythons (Python regius) are snakes, swallow prey whole, hunt at night
In OOP we do the same thing - we create classes as "templates" for objects!
What is Object-Oriented Programming?
OOP is a programming paradigm based on the concept of objects that contain:
- Data (attributes, properties) - describe the object's state
- Behaviors (methods) - describe what the object can do
Key OOP concepts:
- Class - a template, a recipe, a biological species
- Object - a specific instance of a class, a specific animal
- Attributes - the object's data (animal characteristics)
- Methods - functions associated with the object (animal behaviors)
# Simple example - biological classification
class Species:
"""Class representing a species"""
def __init__(self, name, habitat, diet):
"""Constructor - initializes the object"""
self.name = name
self.habitat = habitat
self.diet = diet
def describe(self):
"""Method - describe the species"""
return f"{self.name} - habitat: {self.habitat}, diet: {self.diet}"
# Creating objects (instances of the class)
lion = Species("Lion", "savanna", "meat")
python = Species("Python", "jungle", "rodents")
# Using objects
print(lion.describe()) # "Lion - habitat: savanna, diet: meat"
print(python.describe()) # "Python - habitat: jungle, diet: rodents"This example has two new elements. __init__ is the constructor: Python calls it automatically when an object is created, e.g. Species("Lion", "savanna", "meat"). self is a reference to the current object, this particular animal: self.name = name stores the name in it. We will look at both more closely in the next lesson.
Why OOP?
Without OOP (procedural)
Let's start with the style you already know: every trait of an animal is a separate variable, and the function receives all of them as arguments.
# Data and functions are separate
lion_name = "Lion"
lion_habitat = "savanna"
lion_diet = "meat"
python_name = "Python"
python_habitat = "jungle"
python_diet = "rodents"
def describe_animal(name, habitat, diet):
return f"{name} - habitat: {habitat}, diet: {diet}"
print(describe_animal(lion_name, lion_habitat, lion_diet))
print(describe_animal(python_name, python_habitat, python_diet))With two animals this still works, but every new one means three more variables to track. With twenty species it is easy to mix up the names and pass the function the lion's habitat together with the python's diet.
With OOP
Now the same two animals written as objects: the Animal class keeps the data and the describe() method in one place.
# Data and functions are together in objects
class Animal:
def __init__(self, name, habitat, diet):
self.name = name
self.habitat = habitat
self.diet = diet
def describe(self):
return f"{self.name} - habitat: {self.habitat}, diet: {self.diet}"
lion = Animal("Lion", "savanna", "meat")
python = Animal("Python", "jungle", "rodents")
print(lion.describe())
print(python.describe())The output is the same, but the code is better organized: data and behavior live together, and each new animal is one Animal(...) line instead of three new variables.
4 Pillars of OOP
1. Encapsulation
Grouping data and methods in a single object + hiding implementation details.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute (__)
def deposit(self, amount):
"""Public method"""
if amount > 0:
self.__balance += amount
def get_balance(self):
"""Public access to private attribute"""
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500The balance changes only through the deposit() method, which accepts only positive amounts. Trying to read account.__balance from outside the class raises an AttributeError, because an attribute with two underscores is private.
2. Abstraction
Hiding complexity, showing only the necessary interface.
class Car:
def start_engine(self):
"""Simple interface"""
self.__check_fuel()
self.__ignite_spark_plugs()
self.__start_motor()
print("Engine started!")
def __check_fuel(self):
"""Hidden implementation"""
pass
def __ignite_spark_plugs(self):
"""Hidden implementation"""
pass
def __start_motor(self):
"""Hidden implementation"""
pass
car = Car()
car.start_engine() # Simple interface - no need to know the details!3. Inheritance
Creating new classes based on existing ones - a taxonomic hierarchy!
class Animal:
"""Base class (parent, superclass)"""
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} eats"
class Mammal(Animal):
"""Derived class (child, subclass)"""
def __init__(self, name, fur_color):
super().__init__(name) # Call base class constructor
self.fur_color = fur_color
def nurse_young(self):
return f"{self.name} nurses its young with milk"
lion = Mammal("Lion", "golden")
print(lion.eat()) # Inherited from Animal
print(lion.nurse_young()) # Own Mammal method4. Polymorphism
Different objects can respond to the same method in different ways.
class Dog:
def speak(self):
return "Woof woof!"
class Cat:
def speak(self):
return "Meow!"
class Cow:
def speak(self):
return "Moo!"
# Polymorphism - same method, different behaviors
animals = [Dog(), Cat(), Cow()]
for animal in animals:
print(animal.speak()) # Each one "speaks" differently!Safari example - Species classification
Let's combine these elements in one class: a species has a scientific name, a habitat and a list of observations, and its methods count individuals and assess whether the species is threatened.
class Species:
"""
Class representing a species in the Safari expedition
Analogy: A biological species with shared characteristics
"""
def __init__(self, scientific_name, common_name, habitat, dangerous=False):
"""
Constructor - initializes a new species
Args:
scientific_name: Scientific name (e.g., "Panthera leo")
common_name: Common name (e.g., "Lion")
habitat: Natural environment
dangerous: Whether dangerous to humans
"""
self.scientific_name = scientific_name
self.common_name = common_name
self.habitat = habitat
self.dangerous = dangerous
self.observations = [] # List of observations
def add_observation(self, location, count, notes=""):
"""Add a species observation"""
observation = {
"location": location,
"count": count,
"notes": notes
}
self.observations.append(observation)
print(f"Added observation: {count}x {self.common_name} in {location}")
def get_total_observed(self):
"""Return the total number of observed individuals"""
return sum(obs["count"] for obs in self.observations)
def is_threatened(self):
"""Check if the species is threatened (fewer than 10 observations)"""
return self.get_total_observed() < 10
def get_status(self):
"""Return the species status"""
total = self.get_total_observed()
if total == 0:
return "Not observed"
elif self.is_threatened():
return f"Threatened ({total} individuals)"
else:
return f"Stable ({total} individuals)"
def describe(self):
"""Full species description"""
danger_status = "DANGEROUS" if self.dangerous else "Safe"
return f"""
βββββββββββββββββββββββββββββββββββββββββββββββββ
{self.common_name} ({self.scientific_name})
Habitat: {self.habitat}
Status: {danger_status}
Observations: {len(self.observations)}
Individuals: {self.get_total_observed()}
Condition: {self.get_status()}
βββββββββββββββββββββββββββββββββββββββββββββββββ
""".strip()
# Usage
lion = Species(
scientific_name="Panthera leo",
common_name="Lion",
habitat="savanna",
dangerous=True
)
# Add observations
lion.add_observation("Northern Savanna", 5, "Hunting pride")
lion.add_observation("Rift Valley", 3, "Two adults with cubs")
lion.add_observation("Serengeti Park", 8)
# Display information
print(lion.describe())
print(f"\nTotal observed: {lion.get_total_observed()} lions")
print(f"Is threatened? {'Yes' if lion.is_threatened() else 'No'}")Comparison: Functions vs Classes
Procedural approach (functions and dictionaries)
First, a species as a plain dictionary and three separate functions that create, modify and summarize that dictionary.
def create_species(name, habitat):
"""Returns a dictionary representing a species"""
return {
"name": name,
"habitat": habitat,
"observations": []
}
def add_observation(species_dict, location, count):
"""Modifies the dictionary"""
species_dict["observations"].append({"location": location, "count": count})
def get_total(species_dict):
"""Calculates from the dictionary"""
return sum(obs["count"] for obs in species_dict["observations"])
# Usage - functions and data are separate
lion = create_species("Lion", "savanna")
add_observation(lion, "North", 5)
print(get_total(lion))Object-oriented approach
The same logic as a class: the dictionary keys become attributes of the object, and the functions become its methods.
class Species:
def __init__(self, name, habitat):
self.name = name
self.habitat = habitat
self.observations = []
def add_observation(self, location, count):
"""Data and logic together!"""
self.observations.append({"location": location, "count": count})
def get_total(self):
return sum(obs["count"] for obs in self.observations)
# Usage - data and behaviors together
lion = Species("Lion", "savanna")
lion.add_observation("North", 5)
print(lion.get_total())Advantages of OOP:
- Data and methods are together (logical grouping)
- Easier state management
- Ability to inherit and reuse code
- Better design for complex systems
- Encapsulation protects data
When to use OOP?
Use OOP when:
- Modeling real-world entities (animals, vehicles, users)
- You need many similar objects with different data
- You want to hide implementation details (encapsulation)
- You need hierarchies and inheritance
- Designing an API or library
Use functions/procedures when:
- Simple, linear script
- Stateless data processing
- Utility functions (helper tools)
- You don't need multiple instances
Practical example - Expedition Manager
Finally, a bigger class that runs a whole expedition: it records the team members and the discoveries of each day, and prints a report at the end.
class Expedition:
"""
Class managing a Safari expedition
Combines data (location, team, discoveries) and behaviors (adding, reporting)
"""
def __init__(self, name, leader, start_date):
self.name = name
self.leader = leader
self.start_date = start_date
self.team_members = []
self.discovered_species = []
self.days_elapsed = 0
def add_team_member(self, member_name, role):
"""Add a team member"""
member = {"name": member_name, "role": role}
self.team_members.append(member)
print(f"{member_name} ({role}) joined the expedition")
def discover_species(self, species_name, location, count=1):
"""Record a species discovery"""
discovery = {
"species": species_name,
"location": location,
"count": count,
"day": self.days_elapsed
}
self.discovered_species.append(discovery)
print(f"Day {self.days_elapsed}: Discovered {count}x {species_name} in {location}")
def advance_day(self):
"""Next expedition day"""
self.days_elapsed += 1
print(f"\nDay {self.days_elapsed} of expedition '{self.name}'")
def get_statistics(self):
"""Expedition statistics"""
unique_species = len(set(d["species"] for d in self.discovered_species))
total_animals = sum(d["count"] for d in self.discovered_species)
return {
"expedition": self.name,
"leader": self.leader,
"days": self.days_elapsed,
"team": len(self.team_members),
"unique_species": unique_species,
"total_individuals": total_animals
}
def generate_report(self):
"""Generate expedition report"""
stats = self.get_statistics()
report = f"""
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
EXPEDITION REPORT: {self.name}
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
Leader: {self.leader}
Start date: {self.start_date}
Days in the field: {stats['days']}
Team members: {stats['team']}
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
DISCOVERIES:
- Unique species: {stats['unique_species']}
- Total individuals: {stats['total_individuals']}
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
TEAM:
"""
for member in self.team_members:
report += f"\n - {member['name']} ({member['role']})"
report += "\nββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ"
return report
# Expedition simulation
expedition = Expedition("Safari 2024", "Dr. Jane Wilson", "2024-06-01")
# Add team
expedition.add_team_member("Darwin Brown", "Biologist")
expedition.add_team_member("Alex Chen", "Photographer")
expedition.add_team_member("Maya Patel", "Guide")
# Expedition days
expedition.advance_day()
expedition.discover_species("Panthera leo", "Northern Savanna", 5)
expedition.discover_species("Loxodonta africana", "Elephant Valley", 12)
expedition.advance_day()
expedition.discover_species("Python regius", "Jungle", 2)
expedition.discover_species("Panthera leo", "Southern Savanna", 3)
expedition.advance_day()
expedition.discover_species("Gorilla gorilla", "Cloud Forest", 8)
# Final report
print("\n" + expedition.generate_report())Summary
In this lesson you learned:
- What Object-Oriented Programming (OOP) is
- The difference between procedural and object-oriented approaches
- The 4 pillars of OOP: encapsulation, abstraction, inheritance, polymorphism
- Why OOP is powerful for code organization
- When to use OOP and when to use functions
- Basic concepts: class, object, attribute, method
- Practical Safari examples
Checkpoint
Before moving on:
- You understand the difference between a class and an object
- You know the 4 pillars of OOP (encapsulation, abstraction, inheritance, polymorphism)
- You understand why we group data and behaviors together
- You see the analogy between classes and biological species
- You know when to use OOP and when to use functions
Safari Analogy: A class is a species (Panthera leo), an object is a specific animal (a specific lion named Simba)!
In the next lesson Darwin will teach you how to create your own classes and objects - you'll build a complete species classification system!
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. A class in Python is:
2. The __init__ method is used for:
These are 2 of 4 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for creating a class and object:
- Code editor
Create an Animal class with an __init__ method that accepts name and species and stores them in self.name and self.species
- Code editor
Define an Animal class with __init__(self, name, species) and create an instance of it: tiger = Animal('Tiger', 'Panthera tigris')
- Horizontal ordering
Arrange the header of the Animal class definition:
- Click in order
Click the parts of the header of a constructor that takes a name parameter:
- Vertical ordering
Arrange the lines of an Animal class with a constructor (first method) and a describe() method: