我正在建立一個包含所有吉他音階的庫。有 10 個音階,“Major”、“Minor”、“Major Pentatonic”……每個音階包括 12 個不同的音階,但它們都標有相同的字母。例如; 10個音階
("Major | Minor | Major Pentatonic | Minor Pentatonic | Minor Harmonic | Melodic Minor | Blues | Mixolydian | Dorian | Lydian")
每個量表包括
("C | C#/D? | D | D#/E? | E | F | F#/G? | G | G#/A? | A | A#/B? | B")
所以問題是,在我建立我的第一個方法之后,“主要”規模
def major():
print("\nChoose A Major Scale")
print("C | C#/D? | D | D#/E? | E | F | F#/G? | G | G#/A? | A | A#/B? | B")
answer = input(">")
if answer == "C":
c()
elif answer == "C#/D":
c_sharp_d()
elif answer == "D":
d()
elif answer == "D#/E":
d_sharp_e()
elif answer == "E":
e()
elif answer == "F":
f()
elif answer == "F#/G":
f_sharp_g()
elif answer == "G":
g()
elif answer == "G#/A":
g_sharp_a
elif answer == "A":
a()
elif answer == "A#/B":
a_sharp_b()
elif answer == "B":
b()
else:
print("Thats not an option...")
它作業得很好,但是當我構建第二種方法時,當用戶選擇 12 個音階中的任何一個時,“次要”比例,在次要類別中,它將回傳一個在“主要”類別中構建的比例。現在我知道為什么了,顯然是因為它們已經在“主要”音階中定義,但我的問題是,我怎樣才能解決這個問題,這樣我就不必在 if、elif、else、statments 中更改 12 個音階的名稱每 10 個不同的尺度?當然,我可以為每個不同的比例添加一個字母或數字,比如,
if answer == "C": -- for major
c()
if answer == "C": -- for minor
c1()
so on and so forth, but that doesn't seem very programmatic and there must be a cleaner way to go about it. I was thinking of grouping each individual 10 scales, and their 12 specific scales in their own classes ? Thats where my question lies, if I do that, then will the data only be available within that specific class ? Unless I call that data from the class specifically. For instance, I will still need some methods to be accessible across all classes, like my "main menu" class and such. SO unless its easier to create classes i may just define the different scales like the example above, changing them slightly with just a digit or letter.
note: i come from ruby, and i dont exactly remember classes but im pretty sure that you could encapsulate info that was only usable in that class unless specified.
uj5u.com熱心網友回復:
首先,我的提示是if-else用更優雅和更OCP -y 的東西(例如字典)更改整個大塊:
notes = {'C': c, 'D': d, 'C#/D': c_sharp_d, ...}
并通過用戶提供的輸入呼叫該函式:
notes.get(answer, lambda: 'Thats not an option...')()
(或者現在在 py3.10 中你可以使用結構模式匹配)
如果您希望相同的功能隨著比例的變化而做不同的事情,您可以使用模塊中的singledispatch裝飾器functools:
from functools import singledispatch
@singledispatch
def f_sharp_g():
...
@f_sharp_g.register(Major_Pentatonic)
def _():
""" Do F#/G Major Pentatonic """
uj5u.com熱心網友回復:
你在第二行有縮進錯誤。就在你定義專業之后。它應該像
def major():
print("\nChoose A Major Scale")
print("C | C#/D? | D | D#/E? | E | F | F#/G? | G | G#/A? | A | A#/B? | B")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351216.html
標籤:python python-3.x if-statement
