This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

More Lab exercises

Here are more OOP exercises for you to practise!

Exercises contributed by: Oana Cocarascu

Exercise 1

Create a class Robot where each robot is identified by its name and has two methods, introduce and remove. The class should keep track of the total number of active robots (i.e. robots that have been created) and should have a class method that prints the number of active robots. The introduce method should print the robot’s name. The remove method should decrease the number of active robots and print an appropriate message depending on whether there are any active robots left.

Here is an example of how the classes are expected to be used.

robot1 = Robot('R1')
robot1.introduce()
Robot.number_active_robots()

robot2 = Robot('R2')
robot2.introduce()
Robot.number_active_robots()

robot1.remove()

robot3 = Robot('R3')
robot3.introduce()
Robot.number_active_robots()

robot2.remove()
robot3.remove()

Robot.number_active_robots()

Output:

Hi! I'm R1
There are 1 active robots
Hi! I'm R2
There are 2 active robots
Removing R1
There are still 1 active robots.
Hi! I'm R3
There are 2 active robots
Removing R2
There are still 1 active robots.
Removing R3
R3 was the last robot
There are 0 active robots

Exercise 2

Define and implement the classes required to represent a music playlist: Artist, Song, Album, and Playlist.

Each Song has a title and is associated with an Artist. Each Song also has a year of release.

The Album class should implement a method add_song that takes a title and a release year and creates a new song which is then added to its list of songs.

The Artist class should implement two methods add_album (which takes an album as a parameter) and add_song (which takes a song as a parameter).

The Playlist class should implement a method add_song that adds a song to its list of songs.

Finally,

  • create an artist
  • create an album
  • use add_song from the Album class to add two songs
  • create a song for the artist you have created
  • add all songs from the album to the playlist
  • print all the songs in the playlist
  • print all the artist’s songs

Create any other songs/albums/artists to test your code.