Search code examples
python-2.7classattributeerror

Why this AttributeError?


I'm very new to Python and I was trying to use a nice library (audiotools) to play an mp3 playlist, just as an exercise.

This is the class to play the tracklist (loosely based on THIS, once I discovered there is a "callback function with no arguments which is called by the player when the current track is finished" (*) ):

class Trackplay:
    def __init__(self,
                 track_list,
                 audio_output=audiotools.player.open_output('ALSA'),
                 replay_gain=audiotools.player.RG_NO_REPLAYGAIN):

        self.track_index = INDEX - 1
        self.track_list = track_list

        self.player = audiotools.player.Player(
                audio_output,
                replay_gain,
                self.next_track())

    def next_track(self):
        try:
            self.track_index += 1
            current_track = self.track_list[self.track_index]
            print str(current_track)
            audio_file = audiotools.open(current_track)

            self.player.open(audio_file)   # <---------- error
            self.player.play()
        except IndexError:
            print('playing finished')

Then I'm calling:

tp = Trackplay(get_track_list(PATH))

where get_track_list is a method returning a list of mp3s from the dir PATH.

The error I get (at the line marked with the "error" comment) is:

AttributeError: Trackplay instance has no attribute 'player'

I don't understand what's happening ...but reading all the AttributeError questions here, must be something stupid...

player seems to me exactly a Trackplay's attribute. Other attributes, as track_index and track_list seems OK, since the line print str(current_track) prints the current track.

Thanks for any help.


Solution

  • See this code here?

    self.player = audiotools.player.Player(
            audio_output,
            replay_gain,
            self.next_track())
    

    As part of creating the Player you're going to assign to self.player, you call self.next_track(). self.next_track tries to use self.player, before self.player exists!

    def next_track(self):
        try:
            self.track_index += 1
            current_track = self.track_list[self.track_index]
            print str(current_track)
            audio_file = audiotools.open(current_track)
    
            self.player.open(audio_file)
            self.player.play()
        except IndexError:
            print('playing finished')
    

    next_track doesn't even return anything, so it's baffling why you're trying to pass self.next_track() as an argument to Player.

    Was that supposed to be a callback? If so, you should pass self.next_track to Player without calling it.

    self.player = audiotools.player.Player(
            audio_output,
            replay_gain,
            self.next_track)
    #                     ^ no call parentheses