繁体   English   中英

为什么子 class 的 init 方法也会改变父 class?

[英]Why is the init method for the child class also altering the parent class?

Python 版本:3.8.5

棉花糖:3.9.1

我创建了一种方法来创建 Marshmallow 模式并将属性标签添加到传递到 function 的任何模式中。 您可能会看到下面的示例代码:

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_objchild_schema_obj字段中的所有字段都有x_is_y=True 有谁知道为什么父母和孩子都在更新? 如果是这样,我怎么能只有子 class 的字段具有x_is_y=True属性? 很高兴提供任何其他信息。

你会发现,在y_init中,这个条件成立:

self.fields['example1'].metadata is parent_schema_obj.fields['example1'].metadata

child_y_schema_class字段和SomeSchema字段的元数据字典是同一个字典,当您通过self.fields[field].metadata['x_is_y'] = True修改它时,您会同时修改两者。

目前尚不清楚您要实现什么目标,因此很难就如何采取不同的做法提供指导。 但这回答了“为什么”的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM