创建具有类型的类(“Test”,(Base,),{'__ metaclass __':Meta,...})时__metaclass__不起作用

时间:2016-06-03 09:38:12

标签: python metaclass

cls = type("Test", (Base,), {"__metaclass__": Meta, "a": 1, ...})

我想用Meta类检查第3个参数中的attrs,但这看起来没有用,还有其他方法吗?

2 个答案:

答案 0 :(得分:4)

type - class是cls = Meta("Test", (Base,), {"a": 1, ...}) 的子类。因此,创建一个元类的类型是调用元类:

Function ToolIsEnabled() As Boolean
    Dim rng As Range

    On Error Resume Next
    Set rng = ActiveWorkbook.Range("LoadedToken")
    On Error GoTo 0

    ToolIsEnabled = Not rng is Nothing

End Function

答案 1 :(得分:0)

您应该致电Test(a.k.a。Meta来创建type.__class__.__new__(Meta, "Test", (Base,), {"__metaclass__": Meta, "a": 1})课程。

如果您的字典可能为__metaclass__,则可以使用以下代码:

members = {"__metaclass__": Meta, "a": 1, ...}  
metaclass = members.pop('__metaclass__', type)
cls = metaclass("Test", (Base,), members)