Advertisement
karlakmkj

Instance reference - Exercise 2 (string format)

Jan 5th, 2021
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. '''
  2. Create a function get_song_string that returns a string in the following format: "<song name>" - <artist name> (<song year>)
  3. e.g: "You Belong With Me" - Taylor Swift (2008)
  4. '''
  5.  
  6. class Artist:
  7.     def __init__(self, name, label):
  8.         self.name = name
  9.         self.label = label
  10.  
  11. class Song:
  12.     def __init__(self, name, album, year, artist):
  13.         self.name = name
  14.         self.album = album
  15.         self.year = year
  16.         self.artist = artist
  17.  
  18. #My method
  19. def get_song_string(self):
  20.     return "\"" +  self.name + "\""+ " - " + self.artist.name + " (" + str(self.year) + ")"
  21.  
  22. '''
  23. #Model answer method - alternative string formatting syntax
  24. # By using .format with placeholders
  25. def get_song_string(a_song):
  26.    return '"{0}" - {1} ({2})'.format(a_song.name, a_song.artist.name, a_song.year)
  27. '''
  28. new_artist = Artist("Taylor Swift", "Big Machine Records, LLC")
  29. new_song = Song("You Belong With Me", "Fearless", 2008, new_artist)
  30. print(get_song_string(new_song))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement