【发布时间】:2020-12-17 04:13:24
【问题描述】:
Python 版本:3.8.5
棉花糖:3.9.1
我创建了一个方法来创建 Marshmallow 模式并将属性标签添加到传递给函数的任何模式。您可能会看到下面的示例代码:
from marshmallow import Schema, fields
def _configure_y_subschema(schema):
"""Configures a Y schema wherever Y attributes are necessary.
Args:
schema: The ownership schema to duplicate
Returns:
A `YSchema` that is a duplication of the specified schema
with all fields having `x_is_y = True`
"""
y_dynamic_class = type(
schema.__name__.replace('Schema', 'YSchema'),
(schema,),
{}
)
def y_init(self, *args, **kwargs):
super(y_dynamic_class, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].metadata['x_is_y'] = True
y_dynamic_class.__init__ = y_init
return y_dynamic_class
class SomeSchema(Schema):
example1 = fields.String()
example2 = fields.List(fields.Integer())
parent_schema_obj = SomeSchema()
child_y_schema_class = _configure_y_subschema(SomeSchema)
child_schema_obj = child_y_schema_class()
当我运行生成的代码时,parent_schema_obj 和 child_schema_obj 字段中的所有字段都有 x_is_y=True。有谁知道为什么父母和孩子都在更新?如果是这样,我怎么能只有子类的字段具有x_is_y=True 属性?很高兴提供任何其他信息。
【问题讨论】:
-
Schema的定义在哪里?就此而言,fields的定义在哪里? -
fields和Schema来自棉花糖库@Grismar -
或许在示例开头添加
from marshmallow import Schema, fields语句并指定您使用的 Python 版本和库? -
Python 版本:3.8.5 棉花糖:3.9.1 @Grismar
-
是不是因为你原来的类将东西定义为类变量?
标签: python marshmallow