Python course Β· Module 3: Object-Oriented Programming
Creating your own species
In this lesson11
Welcome back! Darwin here, ready to dive deeper into OOP.
In the previous lesson you learned the concept of classes and objects. Now it's time to learn how to create your own classes from scratch - just like biologists classify new species in the field!
Anatomy of a class in Python
A class consists of several key elements:
class Animal: # 1. Class name (PascalCase)
"""Class documentation - description of what it represents""" # 2. Docstring
species_count = 0 # 3. Class attribute (shared)
def __init__(self, name, age): # 4. Constructor
"""Initializes a new object"""
self.name = name # 5. Instance attributes
self.age = age
Animal.species_count += 1 # Increment counter
def make_sound(self): # 6. Instance method
"""Animal makes a sound"""
return f"{self.name} makes a sound!"
@classmethod # 7. Class method
def get_species_count(cls):
"""Return the number of created animals"""
return cls.species_count
@staticmethod # 8. Static method
def is_adult(age):
"""Check if adult (no access to self/cls)"""
return age >= 2
# Creating objects
lion = Animal("Simba", 3)
elephant = Animal("Dumbo", 5)
print(lion.name) # "Simba" - instance attribute
print(Animal.get_species_count()) # 2 - class method
print(Animal.is_adult(3)) # True - static method1. Defining a class - class
Syntax: class ClassName:
Naming conventions:
- PascalCase (each word capitalized):
Species,AnimalBehavior,DataProcessor - Descriptive name: what the class represents
- Noun, not verb:
Lion, notRunsLion
# Good names
class Species:
pass
class ExpeditionTeam:
pass
class GeneticAnalyzer:
pass
# Bad names
class species: # lowercase
pass
class data: # too generic
pass
class doSomething: # camelCase + verb
pass2. Constructor - __init__
The constructor (__init__) is a special method called automatically when creating an object.
class Species:
def __init__(self, name, habitat):
"""
Constructor - initializes a new species
Args:
name: Species name
habitat: Natural environment
"""
print(f"Creating new species: {name}")
self.name = name # Instance attribute
self.habitat = habitat
self.discovered_date = "2024-01-01" # Default value
# Calling the constructor
lion = Species("Lion", "savanna")
# Automatically calls: Species.__init__(lion, "Lion", "savanna")
# Prints: "Creating new species: Lion"
print(lion.name) # "Lion"
print(lion.habitat) # "savanna"The self parameter
self is a reference to the current object. Python automatically passes the object as the first argument!
class Animal:
def __init__(self, name):
self.name = name # self = current object
# self.name means "the 'name' attribute of THIS object"
def greet(self):
# self allows access to the object's attributes
return f"Hi, I'm {self.name}!"
lion = Animal("Simba")
# Call: lion.greet()
# Python automatically: Animal.greet(lion) β lion becomes self!
elephant = Animal("Dumbo")
# elephant.greet() β Animal.greet(elephant) β elephant is self!
print(lion.greet()) # "Hi, I'm Simba!"
print(elephant.greet()) # "Hi, I'm Dumbo!"NOTE: You can use a different name than self, but it's a strong Python convention!
# Standard (use this!)
def __init__(self, name):
self.name = name
# Technically correct, but DON'T DO THIS
def __init__(this, name): # Like in Java/C#
this.name = name
def __init__(obj, name): # Confusing
obj.name = name3. Instance attributes vs class attributes
Instance attributes
Instance attributes belong to a specific object. Each object has its own values!
class Species:
def __init__(self, name, count):
self.name = name # Instance attribute
self.count = count # Each object has its own value
lion = Species("Lion", 500)
elephant = Species("Elephant", 300)
print(lion.count) # 500 - separate value
print(elephant.count) # 300 - separate value
lion.count = 550 # Changes ONLY the lion
print(lion.count) # 550
print(elephant.count) # 300 - unchanged!Class attributes
Class attributes belong to the class and are shared by all objects!
class Species:
total_species = 0 # Class attribute - shared!
def __init__(self, name):
self.name = name # Instance attribute
Species.total_species += 1 # Increment shared counter
lion = Species("Lion")
elephant = Species("Elephant")
python = Species("Python")
print(Species.total_species) # 3 - the class knows about all!
print(lion.total_species) # 3 - can also access through instance
print(elephant.total_species) # 3 - same value for allWhen to use which?
| Attribute type | When to use | Example |
|---|---|---|
| Instance | Data unique to the object | self.name, self.age |
| Class | Shared data | counters, constants, configuration |
class Species:
# Class attributes
kingdom = "Animalia" # Constant for all
species_count = 0 # Counter
def __init__(self, name, population):
# Instance attributes
self.name = name # Unique for each
self.population = population
Species.species_count += 1
lion = Species("Lion", 500)
elephant = Species("Elephant", 300)
print(Species.kingdom) # "Animalia" - shared
print(lion.name) # "Lion" - unique
print(elephant.name) # "Elephant" - different4. Instance methods
Instance methods operate on a specific object and have access to self.
class Species:
def __init__(self, name, population):
self.name = name
self.population = population
self.observations = []
def add_observation(self, location, count):
"""Add observation - instance method"""
self.observations.append({
"location": location,
"count": count
})
print(f"Observation {self.name}: {count} in {location}")
def get_total_observed(self):
"""Calculate total number of observations"""
return sum(obs["count"] for obs in self.observations)
def is_endangered(self):
"""Check if endangered (< 100 individuals)"""
return self.population < 100
# Usage
lion = Species("Lion", 500)
lion.add_observation("Serengeti", 25)
lion.add_observation("Masai Mara", 18)
print(f"Total observed: {lion.get_total_observed()}") # 43
print(f"Endangered? {lion.is_endangered()}") # False5. Class methods - @classmethod
Class methods operate on the entire class, not on a specific object. They have access to cls.
class Species:
all_species = [] # Registry of all species
def __init__(self, name):
self.name = name
Species.all_species.append(self)
@classmethod
def get_species_count(cls):
"""Return the number of all species"""
return len(cls.all_species)
@classmethod
def find_by_name(cls, name):
"""Find a species by name in the class registry"""
for species in cls.all_species:
if species.name == name:
return species
return None
@classmethod
def clear_registry(cls):
"""Clear the registry"""
cls.all_species.clear()
# Usage
lion = Species("Lion")
elephant = Species("Elephant")
python = Species("Python")
print(Species.get_species_count()) # 3 - class method
found = Species.find_by_name("Elephant")
print(found.name) # "Elephant"Difference self vs cls:
self= specific object (instance)cls= class (type)
6. Static methods - @staticmethod
Static methods have NO access to either self or cls. They are regular functions in the class namespace.
class Species:
@staticmethod
def is_valid_name(name):
"""Check if the species name is valid"""
# No self, no cls - only arguments!
return (
len(name) > 0 and
name[0].isupper() and
" " not in name
)
@staticmethod
def calculate_biodiversity_index(species_count, area_km2):
"""Calculate biodiversity index"""
return species_count / area_km2 if area_km2 > 0 else 0
# Usage - no object needed!
print(Species.is_valid_name("Lion")) # True
print(Species.is_valid_name("lion")) # False - lowercase
print(Species.is_valid_name("")) # False - empty
index = Species.calculate_biodiversity_index(150, 1000)
print(f"Biodiversity index: {index}") # 0.15When to use static methods?
- Helper (utility) functions thematically related to the class
- Validators, converters, calculators
- Don't need access to object or class attributes
Comparison of method types
Let's put the three kinds of methods in one class and check which of them can be called on the class itself and which need an object.
class Species:
species_count = 0 # Class attribute
def __init__(self, name):
self.name = name
Species.species_count += 1
# 1. Instance method - has self
def describe(self):
"""Access to self.name"""
return f"Species: {self.name}"
# 2. Class method - has cls
@classmethod
def get_count(cls):
"""Access to cls.species_count"""
return cls.species_count
# 3. Static method - no self/cls
@staticmethod
def is_valid_name(name):
"""Only arguments, no access to class/object"""
return len(name) > 0
lion = Species("Lion")
# 1. Instance method - needs an object
print(lion.describe()) # OK - works on object
# print(Species.describe()) # ERROR - no object!
# 2. Class method - works on class
print(Species.get_count()) # OK - works on class
print(lion.get_count()) # OK - also works (Python passes the class)
# 3. Static method - always works
print(Species.is_valid_name("Lion")) # OK
print(lion.is_valid_name("Lion")) # OK - also worksSafari example - Species cataloging system
This catalog combines everything from this lesson: class attributes keep a shared species registry, instance methods handle a single species, class methods the whole catalog, and static methods are helpers, such as validating a scientific name.
class SpeciesCatalog:
"""
Complete Safari species cataloging system
Demonstrates all concepts: attributes, methods, constructor
"""
# Class attribute - registry of all species
all_species = {} # {name: Species object}
next_id = 1
def __init__(self, scientific_name, common_name, habitat, diet, dangerous=False):
"""
Constructor - creates a new species in the catalog
Args:
scientific_name: Scientific name (e.g., "Panthera leo")
common_name: Common name (e.g., "Lion")
habitat: Environment ("savanna", "jungle", "mountains", etc.)
diet: Diet ("carnivore", "herbivore", "omnivore")
dangerous: Whether dangerous to humans
"""
# Instance attributes - unique for each species
self.id = SpeciesCatalog.next_id
SpeciesCatalog.next_id += 1
self.scientific_name = scientific_name
self.common_name = common_name
self.habitat = habitat
self.diet = diet
self.dangerous = dangerous
self.observations = [] # List of observations
self.population_estimate = 0
self.conservation_status = "Unknown" # Unknown by default
# Add to class registry
SpeciesCatalog.all_species[scientific_name] = self
# === INSTANCE METHODS (operate on a specific species) ===
def add_observation(self, date, location, count, notes=""):
"""Add a field observation of the species"""
observation = {
"date": date,
"location": location,
"count": count,
"notes": notes
}
self.observations.append(observation)
self.population_estimate += count
return f"Added observation: {count}x {self.common_name}"
def get_total_observed(self):
"""Return the total number of observed individuals"""
return sum(obs["count"] for obs in self.observations)
def update_conservation_status(self):
"""Update conservation status based on population"""
total = self.get_total_observed()
if total == 0:
self.conservation_status = "Not observed"
elif total < 50:
self.conservation_status = "Critically Endangered"
elif total < 250:
self.conservation_status = "Endangered"
elif total < 1000:
self.conservation_status = "Vulnerable"
else:
self.conservation_status = "Least Concern"
return self.conservation_status
def get_risk_level(self):
"""Calculate risk level for the team (0-10)"""
if not self.dangerous:
return 0
# Base risk level for dangerous species
risk = 5
# Increase risk if carnivorous
if self.diet == "carnivore":
risk += 3
# Decrease if population is small (rarely encountered)
if self.get_total_observed() < 50:
risk -= 2
return max(0, min(10, risk)) # Clamp to 0-10
def generate_report(self):
"""Generate a species report"""
self.update_conservation_status()
report = f"""
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ID: {self.id:03d} - {self.common_name.upper()}
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Scientific name: {self.scientific_name}
β Habitat: {self.habitat}
β Diet: {self.diet}
β Dangerous: {'YES' if self.dangerous else 'No'}
β Risk level: {self.get_risk_level()}/10
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β OBSERVATIONS:
β - Total count: {self.get_total_observed()} individuals
β - Number of observations: {len(self.observations)}
β - Conservation status: {self.conservation_status}
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
""".strip()
return report
# === CLASS METHODS (operate on the entire catalog) ===
@classmethod
def get_total_species(cls):
"""Return the number of all registered species"""
return len(cls.all_species)
@classmethod
def find_by_name(cls, scientific_name):
"""Find species by scientific name"""
return cls.all_species.get(scientific_name)
@classmethod
def get_by_habitat(cls, habitat):
"""Return all species from a given habitat"""
return [
species for species in cls.all_species.values()
if species.habitat == habitat
]
@classmethod
def get_dangerous_species(cls):
"""Return all dangerous species"""
return [
species for species in cls.all_species.values()
if species.dangerous
]
@classmethod
def get_most_observed(cls, n=5):
"""Return the n most observed species"""
sorted_species = sorted(
cls.all_species.values(),
key=lambda s: s.get_total_observed(),
reverse=True
)
return sorted_species[:n]
@classmethod
def clear_catalog(cls):
"""Clear the entire catalog (use with caution!)"""
cls.all_species.clear()
cls.next_id = 1
return "Catalog cleared"
# === STATIC METHODS (helper tools) ===
@staticmethod
def validate_scientific_name(name):
"""Validate scientific name (format: "Genus species")"""
parts = name.split()
if len(parts) != 2:
return False
genus, species = parts
# Genus capitalized, species lowercase
return genus[0].isupper() and species[0].islower()
@staticmethod
def calculate_biodiversity_index(species_list):
"""Calculate Simpson's diversity index"""
if not species_list:
return 0.0
total = sum(s.get_total_observed() for s in species_list)
if total == 0:
return 0.0
# Simpson's index: 1 - Ξ£(ni/N)Β²
sum_squares = sum(
(s.get_total_observed() / total) ** 2
for s in species_list
)
return 1 - sum_squares
@staticmethod
def format_scientific_name(genus, species):
"""Format a scientific name: genus capitalized, species in lowercase"""
return f"{genus.capitalize()} {species.lower()}"
# === USAGE DEMONSTRATION ===
print("=== CREATING SPECIES CATALOG ===\n")
# Creating species (constructor)
lion = SpeciesCatalog(
scientific_name="Panthera leo",
common_name="Lion",
habitat="savanna",
diet="carnivore",
dangerous=True
)
elephant = SpeciesCatalog(
scientific_name="Loxodonta africana",
common_name="African Elephant",
habitat="savanna",
diet="herbivore",
dangerous=False
)
python = SpeciesCatalog(
scientific_name="Python regius",
common_name="Royal Python",
habitat="jungle",
diet="carnivore",
dangerous=False
)
crocodile = SpeciesCatalog(
scientific_name="Crocodylus niloticus",
common_name="Nile Crocodile",
habitat="river",
diet="carnivore",
dangerous=True
)
# Adding observations (instance methods)
lion.add_observation("2024-01-15", "Serengeti", 12, "Hunting pride")
lion.add_observation("2024-01-20", "Masai Mara", 8, "Family with cubs")
elephant.add_observation("2024-01-16", "Amboseli", 45, "Large herd")
python.add_observation("2024-01-18", "Congo Jungle", 3)
crocodile.add_observation("2024-01-19", "Nile", 25, "On the riverbank")
# Reports for individual species
print(lion.generate_report())
print()
print(elephant.generate_report())
# Class methods - catalog-wide statistics
print(f"\n=== CATALOG STATISTICS ===")
print(f"Total species count: {SpeciesCatalog.get_total_species()}")
print(f"\nSavanna species:")
for species in SpeciesCatalog.get_by_habitat("savanna"):
print(f" - {species.common_name} ({species.get_total_observed()} individuals)")
print(f"\nDangerous species:")
for species in SpeciesCatalog.get_dangerous_species():
risk = species.get_risk_level()
print(f" {species.common_name} - Risk: {risk}/10")
print(f"\nTop 3 most observed:")
for i, species in enumerate(SpeciesCatalog.get_most_observed(3), 1):
print(f" {i}. {species.common_name}: {species.get_total_observed()} individuals")
# Static methods - tools
print(f"\n=== VALIDATION ===")
names_to_test = ["Panthera leo", "panthera leo", "Lion", "Canis lupus familiaris"]
for name in names_to_test:
valid = "[OK]" if SpeciesCatalog.validate_scientific_name(name) else "[INVALID]"
print(f"{valid} {name}")
# Biodiversity index
all_species_list = list(SpeciesCatalog.all_species.values())
biodiversity = SpeciesCatalog.calculate_biodiversity_index(all_species_list)
print(f"\nBiodiversity index: {biodiversity:.3f}")Summary
In this lesson you learned:
- How to define classes with
class - Creating a constructor with
__init__ - Using
selfto access attributes - The difference between instance and class attributes
- Creating instance, class, and static methods
- When to use each type of method
- Building a complete cataloging system
Checkpoint
Before moving on:
- You can define a class with a constructor
- You understand the difference between
selfandcls - You know the difference between instance and class attributes
- You know when to use
@classmethodvs@staticmethod - You can create an object and call its methods
Key concept: self is "me" - the object refers to itself to access its own data and behaviors!
In the next lesson Darwin will teach you inheritance - how to create class hierarchies like an evolutionary tree!
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 attribute is shared by:
2. By convention, what is the first parameter of an instance method called?
Hands-on tasks in the game
- Click in order
Click elements in the correct order:
- Code editor
Add a speak() method to the Animal class that prints the animal's sound, e.g. 'Simba: Roar!'. Create an animal and call speak()
- Code editor
In the Animal class, add a class attribute kingdom = "Animalia" and an instance attribute name (set in __init__)
- Horizontal ordering
Arrange the elements in the correct order: