Python 使用json映射到特定对象
我在这里看到过加载json文件并将其映射到没有预定属性的任意对象的帖子,但我希望映射到现有对象,因此当我创建新对象时,它们就像类型一样,如果我以后想为该对象添加方法,这不是问题。我尝试向参数中添加**KWARG,但这似乎不起作用,因为我最终得到:Python 使用json映射到特定对象,python,json,Python,Json,我在这里看到过加载json文件并将其映射到没有预定属性的任意对象的帖子,但我希望映射到现有对象,因此当我创建新对象时,它们就像类型一样,如果我以后想为该对象添加方法,这不是问题。我尝试向参数中添加**KWARG,但这似乎不起作用,因为我最终得到: TypeError: __init__() takes 1 positional argument but 2 were given 下面是类和加载方法: import json user_library = [] class Term(obje
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}
因此,有两件事,首先您希望在类中同时考虑位置参数和关键字参数:
class Term():
def __init__(self, *args, **kwargs):
这就是导致错误的原因,因为您试图将term
作为位置参数传递给构造函数,但构造函数不允许这样做
第二,您可以这样传入kwarg字典:
Term(**data_loaded)
这将把您的完整词典作为kwargs
传递到\uuuu init\uuuu
。换句话说,不需要循环