'Override class attributes in Python

Ultimately looking to create a random music scale generator. I’m working on building classes for each mode and wanted to use major or minor scales as a True or False boolyan as a starting point.
Can someone tell me where I’m off with overriding this attribute for Mode2?

Here is my code:

class Mode():

    def __init__(self,title,major):
        self.title = title
        self.major= True


    def __str__(self):
        return "Title: {}, Major: {}".format(self.title,self.major)


Mode1 = Mode("Ionian", "Major")
print(Mode1)

class Mode2(Mode):
    def major(self):
        print(False)


Mode2 = Mode("Dorian", "Minor")
print(Mode2)


Solution 1:[1]

Try a more canonical design. First, I've altered your variables and attributes to reflect Pythonic naming conventions: major => ismajor, canonical case, etc.

With that, I've written a sub-class initialization that calls the parent's init, then makes desired alterations. I'm a bit confused about the major parameter, though: you ignore it and force the majority according to the class used. In any case, here's the result of my fiddling with your design:

class Mode():

    def __init__(self,title,ismajor):
        self.title = title
        self.ismajor= True

    def __str__(self):
        return "Title: {}, Major: {}".format(self.title,self.ismajor)


class Mode2(Mode):

    def __init__(self,title,ismajor):
        super().__init__(title, ismajor)
        self.ismajor= False


mode1 = Mode("Ionian", "Major")
print(mode1)

mode2 = Mode2("Dorian", "Minor")
print(mode2)

Output:

Title: Ionian, Major: True
Title: Dorian, Major: False

If I were doing this, I'd simplify even more: get rid of the different mode classes, and parameterize the one class:

legal_mode = [ 
    "Ionian",
    "Dorian",
    "Phrygian",
    "Lydian",
    "Mixolydian",
    "Aeolian",
    "Locrian"
]
stepping = [2, 2, 1, 2, 2, 2, 1]
major_mode = ["Ionian"]


class Mode():

    def __init__(self,title):
        self.title = title
        self.ismajor = title in major_mode
        tonic = legal_mode.index(title)
        self.stepping = stepping[tonic:] + stepping[:tonic]

    def __str__(self):
        return "Title: {}, Major: {}".format(self.title, self.ismajor)

    def scale_steps(self):
        return "Half-steps: {}".format(' '.join(str(c) for c in self.stepping))

mode1 = Mode("Ionian")
print(mode1)
print(mode1.scale_steps())

mode2 = Mode("Dorian")
print(mode2)
print(mode2.scale_steps())

Output:

Title: Ionian, Major: True
Half-steps: 2 2 1 2 2 2 1
Title: Dorian, Major: False
Half-steps: 2 1 2 2 2 1 2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1