簡體   English   中英

無法遍歷類的列表

[英]Can't iterate through a list of istances of a class

我建立一個列表,其中包含我創建的自定義類的實例。 現在,我可以像這樣訪問單個屬性:

 Name_of_list[Index of specific object].attribute1 

但是:如果我想遍歷bbject,則無法訪問屬性,將出現以下消息:

“ TypeError:'int'對象不可迭代”。

print(list)

[<__main__.Costumer object at 0x00000000118AA3C8>,
<__main__.Costumer object at 0x000000000E3A69E8>,
<__main__.Costumer object at 0x000000000E3A6E10>]

Python使您可以迭代迭代器對象 您不需要為此使用range和索引,Python會在后台為您完成,如以下答案所示

for customer in list:
    print(customer.attribute1)

來自文檔的迭代器定義:

表示數據流的對象。 重復調用迭代器的next ()方法(或將其傳遞給內置函數next())將返回流中的后續項。

您的錯誤在循環初始化行中

for k in 3:

您不能使用in關鍵字進行迭代,您需要對可以使用range生成的序列進行迭代

>>>for k in range(3):
...    print(k)
0
1
2

編輯
我看到我有一些反對意見,所以我想我會嘗試澄清一些東西。
首先,OP的問題是他在一行代碼上遇到錯誤,此后OP的代碼已在編輯中刪除。
代碼在這條路上走了一些路

class MyClass:
    def attribute(self):
        pass

instances = [MyClass(), MyClass(), MyClass()]

for k in 3:
    instances[k].attribute()

並且他收到此錯誤TypeError: 'int' object is not iterable
對於我回答(和OP接受)的錯誤是使用forin您需要的序列。
確實,使用它更具Python性(且更具可讀性)

for ins in instances:
    ins.attribute()

或者是否需要跟蹤當前實例的索引以使用enumerate ,當與可迭代對象一起使用時,它將返回索引和當前對象的元組

for k, ins in enumerate(instances):
    # k will be the current index, and ins will be the current instance.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM