使用 type() 定义 class 对象:为什么我不能使用要深度复制的属性的名称?

Defining a class object with type() : Why can't I use the name of an attribute meant to be deepcopied?

出于某些原因,我不得不使用 type() 函数在 Django 中创建一个表单 class。

我的函数生成器 (makeFurnitureForm()) 的 return 语句如下所示:

    return (type("FurnitureForm",
                 (forms.BaseForm, form_utils.forms.BetterBaseForm,),
                 {"_fieldsets" : dic, "base_fields" : fields,
                  "_fieldset_collection" : None, '_row_attrs' : {}}))

我创建的 class 对象继承自另外两个 classes。 这是其中之一的构造函数:form_utils.forms.BetterBaseForm

    def __init__(self, *args, **kwargs):
        self._fieldsets = deepcopy(self.base_fieldsets)
        self._row_attrs = deepcopy(self.base_row_attrs)
        self._fieldset_collection = None
        super(BetterBaseForm, self).__init__(*args, **kwargs)

我的代码一切正常,但在以前的版本中,我使用了这样的代码:

    return (type("FurnitureForm",
                 (forms.BaseForm, form_utils.forms.BetterBaseForm,),
                 {"base_fieldsets" : dic, "base_fields" : fields}))

由于 _fieldsets_fieldset_collection 是通过深度复制 base_fieldsets 属性并分配 None 值在 BetterBaseForm 构造函数中明确定义和设置的,所以我没有不明白为什么我在尝试访问实例的 _fieldsets_fieldset_collection 属性时得到 AttributeErrors(例如在呈现我的 django 页面时)。

这是我的问题:

  1. 难道type()不调用基本的classes`构造函数,这些构造函数不正确定义和设置属性吗?

  2. 为什么我必须自己明确设置这些属性?

  3. 为什么构造函数尝试时我没有得到 AttributeErrortype() 期间访问属性(例如 row_attrs) 称呼? (虽然我稍后尝试访问它时得到了一个)。

我在我的 django 视图中这样使用我的 makeFurnitureForm() :

return (render(request,'main/devis-bis.html', {"form" : (makeFurnitureForm())()}))

class对象直接传递给视图,然后传递给模板进行渲染。

编辑:回溯和代码。

示例 return :

    return (type("FurnitureForm",
                 (forms.BaseForm, form_utils.forms.BetterBaseForm,),
                 {"base_fieldsets" : dic, "base_fields" : fields,
                  "_fieldset_collection" : None, '_row_attrs' : {}}))

我还发现我直接将一个 class 对象传递给 render() 函数,我不明白为什么它甚至可以工作,因为它需要一个实例。我在 render() 调用中更正了它。

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/forms/forms.py" in __getitem__
  141.             field = self.fields[name]

During handling of the above exception ('fieldsets'), another exception occurred:

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  883.                     current = current[bit]

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/forms/forms.py" in __getitem__
  144.                 "Key %r not found in '%s'" % (name, self.__class__.__name__))

During handling of the above exception ("Key 'fieldsets' not found in 'FurnitureForm'"), another exception occurred:

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/nfs/2013/v/vmonteco/Code/web/demenhouse/htdocs/main/views.py" in secondform
  69.         return (render(request,'main/devis-bis.html', {"form" : makeFurnitureForm()}))

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/shortcuts.py" in render
  67.             template_name, context, request=request, using=using)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
  97.         return template.render(context, request)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/backends/django.py" in render
  95.             return self.template.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render
  206.                     return self._render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render
  992.                 bit = node.render_annotated(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  959.             return self.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  173.         return compiled_parent._render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in _render
  197.         return self.nodelist.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render
  992.                 bit = node.render_annotated(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  959.             return self.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/loader_tags.py" in render
  69.                 result = block.nodelist.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render
  992.                 bit = node.render_annotated(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in render_annotated
  959.             return self.render(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/defaulttags.py" in render
  161.                 values = self.sequence.resolve(context, True)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in resolve
  709.                 obj = self.var.resolve(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in resolve
  850.             value = self._resolve_lookup(context)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/django/template/base.py" in _resolve_lookup
  891.                         current = getattr(current, bit)

File "/nfs/2013/v/vmonteco/Envs/demenhouse/lib/python3.5/site-packages/form_utils/forms.py" in fieldsets
  253.                 self, self._fieldsets)

Exception Type: AttributeError at /devisbis/1679091c5a880faf6fb5e6087eb1b2dc/
Exception Value: 'FurnitureForm' object has no attribute '_fieldsets'
  1. Doesn't type() calls base classes` constructors, and don't these constructors define and set attributes properly?

    您正在查看 初始化程序 ,而不是构造函数,因此得名 __init__。创建实例时会自动调用这些。 type() 不调用这些,因为您不是在生成实例,而是在生成 class.

    一旦调用生成的 class 来创建实例,然后 将调用 __init__ 方法。

  2. Why did I have to explicitly set these attributes by myself?

    我不知道,您没有显示您是如何创建实例的,也没有显示任何其他显示错误的代码。如果您期望这些属性存在于 class,那么您的假设是错误的。

  3. Why didn't I got an AttributeError when the constructor tries to access an attribute (row_attrs for instance) during the type() call? (I got one when trying to access it later though).

    同样,type()产生了一个新的class,不是一个实例,此时__init__没有被调用。

如果 __init__ 方法会将这些属性添加到您的 实例中,则您不需要将这些属性添加到您的 class 命名空间中 命名空间。

我必须注意 forms.BaseForm.__init__ method 不是 旨在与稍后在 MRO 中出现的其他 classes 合作;它从不调用 super().__init__()。如果您确实创建了新 class 的实例,form_utils.forms.BetterBaseForm.__init__() 方法将 不会被调用 ,除非您要交换两个基数 [=] 的顺序85=]es:

return type(
    "FurnitureForm", (form_utils.forms.BetterBaseForm, forms.BaseForm,),
    {"base_fieldsets" : dic, "base_fields" : fields})

这是因为首先列出 BetterBaseForm,它将调用 __init__,然后该方法中的 super(BetterBaseForm, self).__init__(*args, **kwargs) 行将调用 BaseForm.__init__()

阅读您的回溯,我确实注意到您从未创建实例。您应该始终创建表单 class 的实例,并可选择传入 request.POST 以预填充字段并验证表单输入。

所以代替:

return (render(request,'main/devis-bis.html', {"form" : makeFurnitureForm()}))

使用

return render(request,'main/devis-bis.html', {"form" : makeFurnitureForm()()})

注意额外的 ()。但是,您可能想在某个时候检查表单是否 有效 ,因此您可以使用:

form_class = makeFurnitureForm()
if request.method == 'POST':
    form = form_class(request.POST)
    if form.is_valid():
        # ...
        # process data, redirect somewhere
        return HttpResponseRedirect('/thanks/')

else:
    form = form_class()

return render(request,'main/devis-bis.html', {"form" : form})