1

I'm told to

Define a new class, Track, that has an artist (a string), a title (also a string), and an album (see below).

  1. Has a method __init__(self, artist, title, album=None). The arguments artist and and title are strings and album is an Album object (see below)
  2. Has a method __str__(self) that returns a reasonable string representation of this track
  3. Has a method set_album(self, album) that sets this track's album to album

This is my first time working with classes, and I was wondering if someone can explain the difference between using strings and objects in Python. I read up about __str__ also, but I'm not exactly sure how it works. It says the "the string returned by __str__ is meant for the user of an application to see" but I never see the return value for my inputs. Can someone explain the use of __str__ please?

I'm not sure if I followed the guideline correctly either, if someone could confirm what I did is correct, that would be great.

class Track:
    def __init__(self, artist, title, album=None):
        self.artist = str(artist)
        self.title = str(title)
        self.album = album

    def __str__(self):
        return self.artist + " " + self.title + " " + self.album

    def set_album(self, album):
        self.album = album

Track = Track("Andy", "Me", "Self named")
1

1 Answer 1

0

Your class is good for me but if you really want the attributes be strings you should consider use @property decorator and make propper setters and getters. Example below:

class Track:
    def __init__(self, artist, title, album=None):
        self._artist = str(artist)
        self._title = str(title)
        self._album = album

    def __str__(self):
        return self.artist + " " + self.title + " " + self.album
    #example for artist
    @property
    def artist(self):
        return self._artist
    @artist.setter
    def artist(self, artist):
        if artist != type("string"):#ensure that value is of string type.
            raise ValueError
        else:
            self._artist = artist
    #this way you could properly make setters and getter for your attributes
    #same ofr the other stuff

Track = Track("Andy", "Me", "Self named")
3
  • This is over-engineering. One of the great things about Python's classes is that you don't need to fool around with the @property decorator until you really need it. Op, I think your code looks just fine. Commented Oct 8, 2012 at 22:53
  • No need for @property or getters and setters in Python. I'm guessing you also code Obj-C or a similar language? Commented Oct 8, 2012 at 23:00
  • @nathancahill, Im a fully python user :) (but I use c++ too) , my answer was just an example of a simple way of ensuring that when setting values they are strings. Thanks. Commented Oct 9, 2012 at 7:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.