Python 3 — OOP: Inheritance & Dunder Methods
In this final lesson, we will cover inheritance, which allows a child class to inherit attributes and methods from a parent class. We will also explore Dunder (Double-Underscore) methods, which let you customize Python's built-in behaviors on your classes.
Inheritance promotes code reuse. To inherit from a parent class, pass the parent class inside parentheses when declaring the child class. Use super().__init__() to trigger the parent class's constructor:
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
# Child Class
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Run parent constructor
self.breed = breed
def speak(self): # Overriding method
print(f"{self.name} the {self.breed} barks! 🐶")
my_dog = Dog("Rex", "German Shepherd")
my_dog.speak() # Rex the German Shepherd barks!
Dunder methods are built-in methods starting and ending with double underscores (e.g. __init__). By defining them, you tell Python how to interact with your objects during common language operations like printing or checking size:
__str__(self): Dictates what text is returned when the object is printed.__len__(self): Dictates what value is returned whenlen(object)is called.
class Playlist:
def __init__(self, name, songs):
self.name = name
self.songs = songs # list of songs
def __str__(self):
return f"Playlist: {self.name}"
def __len__(self):
return len(self.songs)
my_list = Playlist("Chill Vibes", ["Song 1", "Song 2", "Song 3"])
print(my_list) # Triggers __str__ (Prints: Playlist: Chill Vibes)
print(len(my_list)) # Triggers __len__ (Prints: 3)
You have completed the entire Python 3 Boot Camp track! You now understand the basic building blocks (variables, math, decisions, loops), interactive terminal I/O, file storage, exception safety, and advanced classes. Start writing your own programs in the compiler above to master your skills!
Create a class 'Book' with attributes 'title' and 'author'. Add a '__str__' dunder method that returns: "'[title]' by [author]". Instantiate a book and print it to verify the dunder format.