如何定义具有动态属性的类?

问题描述 投票:0回答:2

在我的项目中,我需要使用dict传递的属性创建一个类,如下所示:

class_attributes = {"sensor": Nested(Sensor),
                    "serial_interface": Nested(SerialInterface)}
class MSchema(marshmallow.ModelSchema):
    class Meta:
        model = cls

    attr = class_attributes

我需要将“传感器”和“ serial_interface”添加到该类中,并且可以使用MSchema.sensorMSchema.serial_interface进行访问。

python class-attributes
2个回答
0
投票

不确定我是否完全理解这个问题,但您是否尝试过使用setattr()

示例代码如下所示:

m_schema = MSchema()
for key, value in class_attributes.items():
    setattr(m_schema, key, value)

[setattr(object, string, value)使用一个对象来设置属性,属性名称的字符串和任意值作为属性值。


0
投票

您可以直接调用ModelSchema的元类,而不用使用class声明式地定义该类。

m = marshmallow.ModelSchema

class_attributes = {
    "sensor": Nested(Sensor),
    "serial_interface": Nested(SerialInterface)
}

m = marshmallow.ModelSchema
mc = type(m)
MSchema = mc('MSchema', (m,), {
    'Meta': type('Meta', (), {'model': cls}),
    **class_attributes
    })

[如果您不知道,class语句只是使用3个参数调用type(或其他一些元类)的声明性语法:类的名称,父类的元组和[ C0]的类属性。 dict语句评估其主体以生成dict,然后调用class(或另一个给定的元类),并将返回值绑定到名称。一些简单的例子:

type
© www.soinside.com 2019 - 2024. All rights reserved.