Python\Marshmallow:TypeError:\uuuu init\uuuuu()缺少1个必需的位置参数:“cls\u或\u实例”

2024-09-30 20:19:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在某个类中定义了以下列表:

class Class1(BaseModel):   # BaseModel is the ORM's base model

    _name = ""
    _year = 0
    .....

    VALUE_LIST = ['a', 'b', 'c]

    def __init__(self, name, year, ........):
        self._name = name
        self._year = year
        ......

在另一个文件中,file_x.py,我导入了类并使用了如下列表:

from myproj.models.class1 import Class1

_value = fields.List(
        attribute='value', data_key='value',
        required=False, allow_none=True, validate=validate.OneOf(Class1.VALUE_LIST, 
              error='value is not allowed'))

然后,当我运行测试时,我得到:

ImportError while loading conftest '/home/ubuntu/PycharmProjects/xmaker_application_manager/xmaker_mgr_app/test/conftest.py'.
__init__.py:5: in <module>
    from xmaker_mgr_app.controllers.user_controller import UserOperator
../controllers/user_controller.py:5: 
in <module>
    from xmaker_mgr_app.bl.user_operator import UserOperator
../bl/user_operator.py:8:
 in <module>
    from xmaker_mgr_app.bl.file_x import UserSchema
../bl/file_x.py:177:
 in <module>
    class Class1Schema(ma.ModelSchema):
../bl/file_x.py:211:
 in Class1Schema
    required=False, allow_none=True, validate=validate.OneOf(Class1.VALUE_LIST, error='value is not allowed'))
E   TypeError: __init__() missing 1 required positional argument: 'cls_or_instance'

我该如何解决这个问题

谢谢


Tags: nameinfrompyimportappvaluevalidate
2条回答

我的错误是我必须使用fields.Str,因为值是Str而不是list

所以

_value = fields.Str(
        attribute='value', data_key='value',
        required=False, allow_none=True, validate=validate.OneOf(Class1.VALUE_LIST, 
              error='value is not allowed'))

解决了这个问题

谢谢大家:)

Python告诉您,您正在尝试调用一个函数(在本例中是类fields.List的构造函数),该函数需要一个名为“cls_或_instance”的位置参数,但您没有提供它

如果您检查如何调用fields.List的构造函数,您会看到您已经按名称提供了几个参数(属性、数据键、允许无等),但其中没有cls或实例

您应该能够通过fields.List(x, ...)fields.List(cls_or_instance=x, ...)来修复此问题。在本例中,x是参数cls_or_instance的值,...是您已经拥有的内容

无论哪种情况,文档都会告诉您哪些参数是必需的,哪些是可选的,以及它们必须是什么

相关问题 更多 >