在实例化过程中递归创建相同的类

时间:2018-07-17 06:20:00

标签: python python-2.7

我有一个想要从中创建字典的json配置。因为json配置是递归的,所以每当我看到一个json值,该值都是要在其上递归迭代的数组。但是,这没有做我想要的事情。

class FieldHandler():
    formfields = {}

    def __init__(self, fields):
        for field in fields:
            options = self.get_options(field)
            f = getattr(self, "create_field_for_" +
                        field['type'])(field, options)
            self.formfields[field['name']] = f

    def get_options(self, field):
        options = {}
        options['label'] = field['name']
        options['help_text'] = field.get("help_text", None)
        options['required'] = bool(field.get("required", 0))
        return options

    def create_field_for_string(self, field, options):
        options['max_length'] = int(field.get("max_length", "20"))
        return django.forms.CharField(**options)

    def create_field_for_int(self, field, options):
            options['max_value'] = int(field.get("max_value", "999999999"))
            options['min_value'] = int(field.get("min_value", "-999999999"))
            return django.forms.IntegerField(**options)

    def create_field_for_array(self, field, options):
            fh = FieldHandler(field['elements'])
            return fh

并实例化:

fh = FieldHandler([
    {'type': 'string', 'name': 'position'}, 
    {'type': 'array', 'name': 'calendar', 'elements': [
        {'type': 'string', 'name': 'country'},    
        {'type': 'string', 'name': 'url'},
    ]},
    {'type': 'int', 'name': 'maxSize'}
])

我希望得到这样的字典:

{
   'position': <django.forms.fields.CharField object at 0x10b57af50>, 
   'calendar': <__main__.FieldHandler instance at 0x10b57c680>, 
   'maxSize': <django.forms.fields.IntegerField object at 0x10b58e050>, 
}

日历本身应为:

{
   'url': <django.forms.fields.CharField object at 0x10b58e150>, 
   'country': <django.forms.fields.CharField object at 0x10b58e0d0>
}

相反,我得到了:

{
   'url': <django.forms.fields.CharField object at 0x10b58e150>, 
   'position': <django.forms.fields.CharField object at 0x10b57af50>, 
   'calendar': <__main__.FieldHandler instance at 0x10b57c680>, 
   'maxSize': <django.forms.fields.IntegerField object at 0x10b58e050>, 
   'country': <django.forms.fields.CharField object at 0x10b58e0d0>
}

我在做什么错?为什么在全局position上设置了countryFieldHandler参数?

1 个答案:

答案 0 :(得分:0)

formfields是在所有实例之间共享的类属性。使其改为实例属性:

class FieldHandler():

    def __init__(self, fields):
        self.formfields = {}
        # ...

现在,所有FieldHandler实例都有自己的formfields,只有“内部”日历处理程序具有countryurl(不假设position这是一个错字)字段。