[英]Print a 2d list from a class in Python?
class Mobile:
def __init__(self, model, type, year):
self.model = model
self.type = type
self.year = year
mobilePhones = [
["Samsung", "Galaxy S8", "2000"],
["Samsung", "Galaxy S9", "2001"],
["Samsung", "Galaxy S10", "2002"],
["Apple", "iPhone 8", "2005"],
["Apple", "iPhone 10", "2006"],
["Apple", "iPhone 11", "2007"],
]
phones = [
Mobile(mobilePhones[0][0],mobilePhones[0][1],mobilePhones[0][2]),
Mobile(mobilePhones[1][0], mobilePhones[1][1], mobilePhones[1][2]),
Mobile(mobilePhones[2][0], mobilePhones[2][1], mobilePhones[2][2]),
Mobile(mobilePhones[3][0], mobilePhones[3][1], mobilePhones[3][2]),
Mobile(mobilePhones[4][0], mobilePhones[4][1], mobilePhones[4][2]),
Mobile(mobilePhones[5][0], mobilePhones[5][1], mobilePhones[5][2]),
]
print(phones.model)
我只是想知道為什么這個邏輯不起作用? 我正在嘗試將 2dlist 中的每個數據添加到 class,這樣我就可以調用所有 model、類型或年份。
print(mobilePhones[0][1])
有效,但當我嘗試從 class 調用它時無效。 喜歡:
print(phones.model) or print(phones.year).
因為phones
是一個list
object。 您需要通過索引/循環訪問其有序的內容/對象。 然后在這些內容/對象上,您可以調用它提供的可調用對象。
您不是試圖從 class 使用phones.model
訪問它。 您正在嘗試從列表中訪問它。 您需要先 select 索引,即phones[0].model
。 或者如果你想打印所有這些的 model,
for phone in phones:
print(phone.model)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.