HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Music note class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
musicnoteclass

Problem

A class for notes calculation.

#!/usr/bin/env python3

from string import ascii_uppercase

class Notes:
    notes = ascii_uppercase[:7]
    notes_number = range(7)
    notes_dict = dict(zip(notes, notes_number))
    numbers_dict = dict(zip(notes_number, notes))

    def __init__(self, _note):
        if not _note in Notes.notes:
            raise Exception("Not a valid note")
        self.note = _note
        self.note_number = Notes.notes_dict[self.note]

    def add(self, n):
        if not n in range(8):
            raise Exception("Not a valid number")

        old_number = Notes.notes_dict[self.note]
        new_number = (old_number + n) % 7
        return Notes.numbers_dict[new_number]

    def minus(self, n):
        if not n in range(8):
            raise Exception("Not a valid number")

        old_number = Notes.notes_dict[self.note]
        new_number = (old_number - n) % 7
        return Notes.numbers_dict[new_number]


Test:

x = Notes("G")
x.add(7)

Solution


  • __init__ assigns self.note_number, but the other functions don't use it, instead they look up the number from the dict. Choose one approach and eliminate the other.



  • Checking the range of n and raising the exception in add and minus is not necessary, because the computation has a valid result for all numbers.



  • add and minus are almost the same. One function that allows a negative argument would suffice. If you want to keep minus implement it simply as return self.add(-n)

Context

StackExchange Code Review Q#71863, answer score: 6

Revisions (0)

No revisions yet.