2

我正在尝试从 wtforms 的默认字段类创建子类。

class MyForm(Form):
    fieldName = MyField('field name')

并且 MyField 是从另一个文件导入的

class MyField(TextField):
    def __init__(self):
        super(MyField, self).__init__(**kwargs)

但是当我创建一个源自这里的 MyForm 时出现一些错误:

In [5]: f = MyForm()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
path/<ipython-input-5-decc3699f7c4> in <module>()
----> 1 f = RegistrationForm()

path/wtforms/form.pyc in __call__(cls, *args, **kwargs)
    176             fields.sort(key=lambda x: (x[1].creation_counter, x[0]))
    177             cls._unbound_fields = fields
--> 178         return type.__call__(cls, *args, **kwargs)
    179 
    180     def __setattr__(cls, name, value):

path/wtforms/form.pyc in __init__(self, formdata, obj, prefix, **kwargs)
    222             of a matching keyword argument to the field, if one exists.
    223         """
--> 224         super(Form, self).__init__(self._unbound_fields, prefix=prefix)
    225 
    226         for name, field in iteritems(self._fields):

pathwtforms/form.pyc in __init__(self, fields, prefix)
     37 
     38         for name, unbound_field in fields:
---> 39             field = unbound_field.bind(form=self, name=name, prefix=prefix, translations=translations)
     40             self._fields[name] = field
     41 

path/wtforms/fields/core.pyc in bind(self, form, name, prefix, translations, **kwargs)
    299 
    300     def bind(self, form, name, prefix='', translations=None, **kwargs):
--> 301         return self.field_class(_form=form, _prefix=prefix, _name=name, _translations=translations, *self.args, **dict(self.kwargs, **kwargs))
    302 
    303     def __repr__(self):

TypeError: __init__() got an unexpected keyword argument '_form'

我想 _form 字段没有正确实例化。任何想法如何做到这一点?谢谢

4

1 回答 1

1

您的MyField.__init__方法缺少必要的关键字 args。试试这个:

class MyField(TextField):
    def __init__(self, **kwargs):  # You were missing the **kwargs
        super(MyField, self).__init__(**kwargs)

函数调用中的***运算符(?)执行以下操作:

  • 如果在函数签名中使用,它们指定所有剩余的位置 ( *) 或关键字 ( **) 参数应放置在tuple/ dict(分别)中,并且数据应绑定到*/后面的名称**
  • 如果在函数调用中使用,它们指定tupleor list(for *) 或dict(for **) 应该被解包并作为参数/关键字参数列表传递给函数。
于 2012-09-18T15:40:22.733 回答