Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.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私有前缀_Python_Json_Python 3.x_Private - Fatal编程技术网

去掉Python私有前缀

去掉Python私有前缀,python,json,python-3.x,private,Python,Json,Python 3.x,Private,我有这样一个自定义类: import json class Config: def __init__(self): self._field1 = None self._field2 = None @property def field1(self): return self._field1 @field1.setter def field1(self, value): self._fie

我有这样一个自定义类:

import json

class Config:
    def __init__(self):
        self._field1 = None
        self._field2 = None

    @property
    def field1(self):
        return self._field1

    @field1.setter
    def field1(self, value):
        self._field1 = value

    @property
    def field2(self):
        return self._field2

    @field2.setter
    def field2(self, value):
        self._field2 = value

    def validate(self):
        fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
        for field in fields:
            if getattr(self, field) == None:
                raise AttributeError("You must set all fields, " + str(field) + " is not set")

    def toJSON(self):
        return json.dumps(self, default=lambda o: vars(o), 
            sort_keys=True, indent=4)
正如您所看到的,我尝试用JSON序列化我的类,但它总是在JSON中包含uu前缀(因为vars将返回该前缀)

问题1:我如何摆脱它

问题2:我试图从类中删除前缀,但在调用构造函数时会出现“错误:调用Python对象时超过最大递归深度”。为什么会这样

稍后,我可能会向setter添加验证逻辑


另外,如果您对如何重构我的代码有任何建议,请不要对自己保密。

这可能有些过分,但这是可行的:

import json

class _ConfigSerializable:
    __dict__ = {}
    def __init__(self, config):
        for x, y in config.__dict__.items():
            while x.startswith("_"):
                x = x[1:]
            self.__dict__[x] = y

class Config:
    def __init__(self):
        self._field1 = None
        self._field2 = None

    @property
    def field1(self):
        return self._field1

    @field1.setter
    def field1(self, value):
        self._field1 = value

    @property
    def field2(self):
        return self._field2

    @field2.setter
    def field2(self, value):
        self._field2 = value

    def validate(self):
        fields = [attribute for attribute in dir(self) if not attribute.startswith('__') and not callable(getattr(self, attribute))]
        for field in fields:
            if getattr(self, field) == None:
                raise AttributeError("You must set all fields, " + str(field) + " is not set")

    def toJSON(self):
        s = _ConfigSerializable(self)
        return json.dumps(s, default=lambda o: vars(o), 
            sort_keys=True, indent=4)

print(Config().toJSON())
输出:

{
    "field1": null,
    "field2": null
}

基本上,我们创建一个新类,该类接受config实例的属性,并创建一个字典,删除任何属性名称开头的
。然后我们将该类实例序列化。

为什么需要??这是必需的吗?这回答了你的问题吗?产生递归错误是因为在构造函数中初始化变量,从而调用setter函数。这些函数更改变量中的值,因此调用setter函数,etc@Akhilesh_uu应表示一个私有字段,因为以后我想向setters添加验证逻辑,我不想在setters之外修改实例变量。@EdWard你能告诉我为什么在这里发生这种情况而不是在“private”字段中发生吗?我找不到关于这方面的任何文档。这是一种比这更好的方法吗?由你决定。我的方法可行,而且我想更容易扩展,但答案是代码更少,而且可能更有效。:)