Python:元类一直在下降

2024-10-03 00:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个涉及Python元类的深奥问题。我正在为web服务器端代码创建一个Python包,它将使通过客户端代理访问任意Python类变得容易。我的代理生成代码需要包含在API中的所有Python类的目录。为了创建这个目录,我使用__metaclass__特殊属性将一个钩子放入类创建过程中。具体地说,“已发布”API中的所有类都将子类化一个特定的基类PythonDirectPublic,该基类本身有一个__metaclass__,该基类已设置为记录有关类创建的信息。在

到目前为止还不错。更复杂的是我想让我的PythonDirectPublic本身从第三方类(enthought.traits.api.HasTraits)继承。这个第三方类也使用__metaclass__。在

那么管理两个元类的正确方法是什么呢?我的元类应该是enthough的元类的一个子类吗?或者我应该在我的元类的__new__方法中调用enhown的元类来获得我将返回的类型对象吗?或者在这种特殊情况下还有其他神秘咒语可以使用吗?在


Tags: 方法代码目录apiweb客户端代理属性
2条回答

Specifically, all of the classes in the "published" API will subclass a particular base class, PythonDirectPublic

您可以递归地使用PythonDirectPublic的结果,而不是添加另一个元类。子类()。在

Should my metaclass be a subclass of Enthought's metaclass?

我相信这是你唯一的选择。如果派生类的元类不是其所有基元类的子类,那么当您尝试创建派生类时,Python将抛出一个TypeError。因此,PythonDirectPublic的元类应该类似于

class DerivedMetaClass(BaseMetaClass):
    def __new__(cls, name, bases, dct):
        # Do your custom memory allocation here, if any

        # Now let base metaclass do its memory allocation stuff
        return BaseMetaClass.__new__(cls, name, bases, dct)

    def __init__(cls, name, bases, dct):
        # Do your custom initialization here, if any
        # This, I assume, is where your catalog creation stuff takes place

        # Now let base metaclass do its initialization stuff
        super(DerivedMetaClass, cls).__init__(name, bases, dct)

如果您无权访问第三方基类的元类定义,可以将BaseMetaClass替换为enthought.traits.api.HasTraits.__metaclass__。虽然很冗长,但会有用的。在

相关问题 更多 >