python - 使用 type() 定义类对象 : Why can't I use the name of an attribute meant to be deepcopied?

标签 python django attributeerror

由于某些原因,我必须使用 type() 函数在 Django 中创建一个表单类。

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

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

我创建的类对象继承自其他两个类。 这是其中之一的构造函数: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 属性并在 BetterBaseForm 构造函数中显式定义和设置的None 值,我不明白为什么在尝试访问 _fieldsets_fieldset_collection 属性时出现 AttributeError一个实例(例如渲染我的 django 页面时)。

这是我的问题:

  1. type() 不是调用基类的构造函数吗?这些构造函数没有正确定义和设置属性吗?

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

  3. 当构造函数尝试执行以下操作时,为什么我没有得到 AttributeErrortype() 期间访问属性(例如 row_attrs) 称呼? (不过,当我稍后尝试访问它时,我得到了一个)。

我在 django View 中使用我的 makeFurnitureForm() :

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

类对象直接传递给 View ,然后传递给要渲染的模板。

编辑:回溯和代码。

此返回示例:

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

我还发现我直接将一个类对象传递给 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() 不会调用这些,因为您没有生成实例,而是生成一个

    一旦调用生成的类来创建实例,就会调用 __init__ 方法。

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

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

  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() 生成一个新类,而不是实例,并且此时不会调用 __init__

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

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

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__()

阅读您的回溯,我确实注意到您从未创建实例。您应该始终创建表单类的实例,并可选择传入 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})

关于python - 使用 type() 定义类对象 : Why can't I use the name of an attribute meant to be deepcopied?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407768/

相关文章:

python - 以负步幅到达序列开头的扩展切片

python - Python 2.7 中出现 "ImportError: cannot import name HTTPSConnection"错误

python - 为什么 joblib 并行执行会使运行时慢很多?

python - 使用变量进行 Django 对象过滤

python - 为什么会出现这个属性错误呢?

Python,实例没有 __call__ 方法

python - Dask:非常低的 CPU 使用率和多线程?这是预期的吗?

Django 模型表单 "unique=True"

python - 如何在 django 中访问媒体文件

python - AttributeError: 模块 'datetime' 没有属性 'time'