Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在包含基于json键的self关键字的类中定义_uinit__u;函数_Python_Json_Rest - Fatal编程技术网

Python 如何在包含基于json键的self关键字的类中定义_uinit__u;函数

Python 如何在包含基于json键的self关键字的类中定义_uinit__u;函数,python,json,rest,Python,Json,Rest,我有一个json str,其中包含一个来自API的名为“self”的键。通常情况下,您希望将字典传递给类,但其中一个给定键(self)导致出现问题。不足为奇。但我不知道如何修复它 我的班级是这样的: class Issue: def __init__(self, expand, fields, key, self): self.expand = expand self.assignee = fields['assignee']['displayName']

我有一个json str,其中包含一个来自API的名为“self”的键。通常情况下,您希望将字典传递给类,但其中一个给定键(self)导致出现问题。不足为奇。但我不知道如何修复它

我的班级是这样的:

class Issue:
    def __init__(self, expand, fields, key, self):
        self.expand = expand
        self.assignee = fields['assignee']['displayName']
        self.key = key
        self.self = self
    
    @classmethod
    def from_json(cls, json_dict):
        return cls(**json_dict)
要实例化我写入的对象,请执行以下操作:

Issue.from_json(json_dictionary)
我收到无法修复的类型错误:

TypeError: __init__() got multiple values for argument 'self'
我已经尝试过不同版本的前导下划线等,但这没有帮助。如果我这样做:

class Issue:
    def __init__(self, expand, fields, key, aSelf):
        self.expand = expand
        self.assignee = fields['assignee']['displayName']
        self.key = key
        self.self = aSelf
    
    @classmethod
    def from_json(cls, json_dict):
        return cls(**json_dict)

错误消息保持不变。您能给我解释一下如何处理这些问题吗?

调用方法的第一个参数
self
只是一种惯例。这个名字并不特别。从技术上讲,你不必这么说。如果你有一个很好的理由,你可以把它叫做别的东西:

def __init__(self_, expand, fields, key, self):
    self_.expand = expand
    self_.assignee = fields['assignee']['displayName']
    self_.key = key
    self_.self = self

这是因为
json\u字典中的键与类的构造函数不匹配。请尝试以下操作:

班级问题:
定义初始值(**kwargs):
如果在kwargs中“展开”:
_自我扩展=kwargs['expand']
... # 其他值也一样
@类方法
来自_json的定义(cls,json_dict):
返回cls(**json_dict)

这不会解决“参数'self'的多个值”问题。这不会起作用,因为如果您将
self
键放入
**kwargs
中,Python解释器在处理参数时会遇到相同的问题(double-
self
将是不明确的)。好的,可能是,如果在
json_dict
中有一个
self
键。更新了答案。此外,我的解决方案将在
json_dict
中使用任意数量的键,因为
json_dict
包含键
self
,当您使用
**json_dict
时,无论您在
\u init
签名中定义了哪个参数名称,该解决方案都不起作用;Python将把来自
json_dict
的所有键作为参数名传递,并将它们的值作为参数传递,因此您将得到另一个
self
。要使其工作,您需要将
中的
json\u dict
更改为
self
,并将key
self
重命名为
aSelf