1
我已經看到這裏的帖子加載一個json文件並將其映射到一個沒有預定屬性的任意對象,但我想映射到一個現有的對象,所以當我創建新的對象時,它們就像類型,如果我想在稍後爲該對象添加方法,這不是問題。我嘗試添加** kwargs的參數,但是這似乎並沒有工作,因爲我結束了:用json映射到特定的對象
TypeError: __init__() takes 1 positional argument but 2 were given
這裏的類加載方法:
import json
user_library = []
class Term(object):
def __init__(self, **kwargs):
self.term = None
self.type = None
self.translation = None
self.learned = None
self.diffculty = None
self.streak = None
self.totalCorrect = None
self.totalAttempts = None
self.lastViewed = None
for key in kwargs:
setattr(self, key, kwargs[key])
def load(file='data/user_library.json'):
with open(file) as data_file:
data_loaded = json.load(data_file)
for term in data_loaded:
user_library.append(Term(term))
下面是一個例子我想要傳遞給構造函數:
{'diffculty': None, 'translation': 'to have', 'totalCorrect': None, 'learned': False, 'term': 'avoir', 'streak': None, 'type': 'verb', 'totalAttempts': None, 'lastViewed': 1502899731.261366}