最终希望创建一个随机的音阶发生器。我正在为每种模式构建班级,并希望以大或小比例作为True或False boolyan作为起点。
有人可以告诉我要覆盖Mode2的此属性的地方吗?
这是我的代码:
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)
答案 0 :(得分:0)
尝试更规范的设计。首先,我更改了变量和属性以反映Python的命名约定:major => ismajor,规范大小写等。
这样,我编写了一个子类初始化,该初始化调用父级的init
,然后进行所需的更改。不过,我对major
参数有些困惑:您忽略它,并根据所使用的类强制使用大多数参数。无论如何,这是我对您的设计不满意的结果:
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)
输出:
Title: Ionian, Major: True
Title: Dorian, Major: False
如果我这样做,我将进一步简化:摆脱不同的模式类,并参数化一个类:
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())
输出:
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