为动态类型指定元类

specify metaclass for dynamic type

在Python中,您可以使用函数my_type = type(name, bases, dict)动态创建类型。您将如何为这种类型 my_type 指定元类? (理想情况下,除了定义一个简单地将元类绑定到实例化子类的一次性 class 对象)

对于Dynamic Type Creation where you need to provide keywords in the class statement (including, but not limited to, the keyword "metaclass"), you would use types.new_class。以下class定义:

class A(B, C, metaclass=AMeta):
    pass

可以像这样动态创建:

A = types.new_class(
    name="A",
    bases=(B, C),
    kwds={"metaclass": AMeta},
    exec_body=None,
)

这比直接调用 type 或任何其他元class 更可取,因为它解析了元class 基 - 取决于 B 的类型和C,这里的type(A)might not necessarily be AMeta