簡體   English   中英

如何在循環中實例化一個對象並將每個實例添加到列表中?

[英]How can i instantiate an object in a loop and add each instance to a list?

嗨,我在這里收到錯誤消息:AttributeError: 'dict' object has no attribute 'tag' 這是我的代碼:

class Move:
    def __init__(self, tag, quantity, date):
        self.tag = tag
        self.quantity = quantity
        self.date = date

moves_list = []
const_weight = 15

def last_tag():
    JSON_file = open('movements.json')
    myList = json.load(JSON_file)
    JSON_file.close()
    print(myList[-1].tag)
    return myList[-1].tag

def last_date():
    JSON_file = open('movements.json')
    myList = json.load(JSON_file)
    JSON_file.close()
    print(myList[-1].date)
    return myList[-1].date
while True:
    tag_rilevato = last_tag()
    if my_tag == last_tag():
            m = Move(my_tag, const_weight, last_date())
            moves_list.append(m)

我不明白myList[-1].tagmyList[-1].quantitymyList[-1].date是否有問題? 任何人都可以提出一些建議,非常感謝

您需要將json.load()的返回作為字典訪問,而不是您的Move對象。 所以使用['tag']而不是.tag 像這樣:

def last_tag():
    with open('movements.json', 'r') as fh:
        myList = json.load(fh)
    return myList[-1]['tag']

def last_date():
    with open('movements.json', 'r') as fh:
        myList = json.load(fh)
    return myList[-1]['date']

# Rest of code is unchanged

我還將文件讀/寫更改為推薦with open() as..語法。 當然,這不是解決您的問題所必需的。

暫無
暫無

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

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