Editor

Refactor a Playlist with Magic Methods

Advanced · Refactor · from Python Magic Methods: The Complete __dunder__ Guide

From the lesson: Python Magic Methods: The Complete __dunder__ Guide

Think of a TV remote control. You press the volume button, and the TV gets louder. You press the channel button, and it switches channels. You don't think about how it works - you just press the button and the TV responds.

Read the lesson

Refactor this Playlist class to use magic methods instead of regular methods. Replace get_song(index) with __getitem__, song_count() with __len__, has_song(name) with __contains__, and display() with __str__. Then create a playlist with the name 'Rock', add 'Thunder' and 'Highway', and print the playlist, its length, and whether it contains 'Thunder'.

class Playlist:
def __init__(self, name):
self.name = name
self.songs = []
def add(self, song):
self.songs.append(song)
def get_song(self, index):
return self.songs[index]
def song_count(self):
return len(self.songs)
def has_song(self, name):
return name in self.songs
def display(self):
return f'{self.name}: {", ".join(self.songs)}'
# Refactor the class above, then test it

More Magic Methods exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz