[英]Python. How can I output each instance of a for loop as a nested list, lists inside a list
[英]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].tag
或myList[-1].quantity
或myList[-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.