2017-08-16 171 views
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} 

回答

1

所以,几件事情,首先要允许在您的课内外位置和关键字参数:

class Term(): 

    def __init__(self, *args, **kwargs): 

这就是导致错误的原因是你试图将term作为位置参数传递给构造函数,但构造函数不允许这样做。

其次,你可以通过你的kwarg字典中是这样的:

Term(**data_loaded) 

这将通过您的完整字典作为kwargs__init__。换句话说,不需要循环。