Python Programming Blueprints
上QQ阅读APP看书,第一时间看更新

Adding menus for albums and track selection

Now, we are going to create a file called menu_item.py in the musicterminal/client/ directory and we will start by importing some functions that we will need:

from uuid import uuid1

We only need to import the uuid1 function from the uuid module because, like the panels, we are going to create an id (GUID) for every menu item in the list.

Let's start by adding the class and the constructor:

class MenuItem:
def __init__(self, label, data, selected=False):
self.id = str(uuid1())
self.data = data
self.label = label

def return_id():
return self.data['id'], self.data['uri']

self.action = return_id
self.selected = selected

The MenuItem initializer gets three arguments, the label item, the data which will contain the raw data returned by the Spotify REST API, and a flag stating whether the item is currently selected or not.

We start off by creating an id for the item, then we set the values for the data and label properties using the argument values that are passed in the class initializer.

Every item in the list will have an action that will be executed when the item is selected on the list, so we create a function called return_id that returns a tuple with the item id (not the same as the id that we just created). This is the id for the item on Spotify, and the URI is the URI for the item on Spotify. The latter will be useful when we select and play a song.

Now, we are going to implement some special methods that will be useful for us when performing item comparisons and printing items. The first method that we are going to implement is __eq__:

def __eq__(self, other):
return self.id == other.id

This will allow us to use the index function to find a specific MenuItem in a list of MenuItem objects.

The other special method that we are going to implement is the __len__ method:

def __len__(self):
return len(self.label)

It returns the length of the MenuItem label and it will be used when measuring the length of the menu item labels on the list. Later, when we are building the menu, we are going to use the max function to get the menu item with the longest label, and based on that, we'll add extra padding to the other items so that all the items in the list look aligned.

The last method that we are going to implement is the __str__ method:

def __str__(self):
return self.label

This is just for convenience when printing menu items; instead of doing print(menuitem.label), we can just do print(menuitem) and it will invoke __str__, which will return the value of the MenuItem label.