Classes, Objects & Inheritance
Build custom types using classes, encapsulate behavior with methods, and reuse code with inheritance.
Learning objectives
- Define classes with constructor __init__ and self instance parameter
- Implement single inheritance using super() to invoke parent behavior
Lesson material
Class Definition and Objects
Classes act as blueprints for creating objects that combine data (attributes) and behavior (methods).
Example code
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def speak(self):
return f"{self.name} barks!"
dog = Dog("Buddy")
print(dog.speak())
Practice exercise: Create a Car Class
Create a class `Car` with `__init__(self, make, speed)`. Add a method `drive(self)` that prints `f"{self.make} driving at {self.speed} km/h"`. Create `Car("Toyota", 100)` and call `drive()`.
Test yourself with the Module 10: Object-Oriented Programming (OOP) quiz →