我有一个涉及Python元类的深奥问题。我正在为web服务器端代码创建一个Python包,它将使通过客户端代理访问任意Python类变得容易。我的代理生成代码需要包含在API中的所有Python类的目录。为了创建这个目录,我使用__metaclass__
特殊属性将一个钩子放入类创建过程中。具体地说,“已发布”API中的所有类都将子类化一个特定的基类PythonDirectPublic
,该基类本身有一个__metaclass__
,该基类已设置为记录有关类创建的信息。在
到目前为止还不错。更复杂的是我想让我的PythonDirectPublic
本身从第三方类(enthought.traits.api.HasTraits
)继承。这个第三方类也使用__metaclass__
。在
那么管理两个元类的正确方法是什么呢?我的元类应该是enthough的元类的一个子类吗?或者我应该在我的元类的__new__
方法中调用enhown的元类来获得我将返回的类型对象吗?或者在这种特殊情况下还有其他神秘咒语可以使用吗?在
您可以递归地使用PythonDirectPublic的结果,而不是添加另一个元类。子类()。在
我相信这是你唯一的选择。如果派生类的元类不是其所有基元类的子类,那么当您尝试创建派生类时,Python将抛出一个TypeError。因此,
PythonDirectPublic
的元类应该类似于如果您无权访问第三方基类的元类定义,可以将
BaseMetaClass
替换为enthought.traits.api.HasTraits.__metaclass__
。虽然很冗长,但会有用的。在相关问题 更多 >
编程相关推荐