我剛剛開始學習如何編碼,所以如果您在這里發現任何錯誤,請警告我。
我有一堂課:
class Wii:
def __init__(self, color, gamecube_comp, miinum, installed_games):
self.color = color
self.gamecube_comp = gamecube_comp
self.miinum = miinum
self.installed_games = installed_games
我希望能夠根據外部字典和一些輸入從這個類中列印屬性,所以我嘗試了這個:
selections = {
"1": Wii_1,
"2": Wii_2,
"color": color,
"gamecube_comp": gamecube_comp,
"miinum": miinum,
"installed_games": installed_games
}
selected_wii = input("Select a Wii from the list (just the number)\n")
selected_att = input("State what you want to know about the selected Wii\n")
print(selections[selected_wii].selections[selected_att])
但它不允許我列印,因為selections沒有在類中定義。selections[selected_att]有沒有辦法讓它即使不在課堂上也能閱讀?
uj5u.com熱心網友回復:
如果您將屬性名稱作為文本(字串),則從現有實體中檢索它的推薦方法是使用getattr內置的:
print(getattr(selections[selected_wii], selected_att))
Python 語言選擇在源代碼中硬編碼的屬性名稱與鍵名稱不同,其中鍵是用于檢索相應映射值的任意資料。這與 Javascript 形成對比,例如,兩者都可以互換。但是,與靜態型別語言相比,在運行時無法或很難檢索源代碼中命名為資料的屬性或欄位,Python 提供了易于使用的自省功能,例如. getattr稱呼。所以,當你的設計需要這種用法時,你可以自由地去做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/432212.html
上一篇:Tkinter-標簽不更新
