Python:元类一直向下
我有一个涉及 Python 元类的深奥问题。我正在为 Web 服务器端代码创建一个 Python 包,以便通过客户端代理轻松访问任意 Python 类。我的代理生成代码需要我想要包含在 API 中的所有 Python 类的目录。为了创建这个目录,我使用 __metaclass__ 特殊属性将一个钩子放入类创建过程中。具体来说,“已发布”API 中的所有类都将子类化特定基类 PythonDirectPublic
,该基类本身具有一个 __metaclass__
,已设置为记录有关班级创建。
到目前为止,一切都很好。事情变得复杂的是,我希望我的 PythonDirectPublic 本身继承第三方类 (enthought.traits.api.HasTraits)。此第三方类还使用__metaclass__
。
那么管理两个元类的正确方法是什么?我的元类应该是 Enthought 元类的子类吗?或者我应该在元类的 __new__
方法中调用 Enthought 的元类来获取我将返回的类型对象?或者在这种特殊情况下还有其他神秘咒语可以使用吗?
I have an esoteric question involving Python metaclasses. I am creating a Python package for web-server-side code that will make it easy to access arbitrary Python classes via client-side proxies. My proxy-generating code needs a catalog of all of the Python classes that I want to include in my API. To create this catalog, I am using the __metaclass__
special attribute to put a hook into the class-creation process. Specifically, all of the classes in the "published" API will subclass a particular base class, PythonDirectPublic
, which itself has a __metaclass__
that has been set up to record information about the class creation.
So far so good. Where it gets complicated is that I want my PythonDirectPublic
itself to inherit from a third-party class (enthought.traits.api.HasTraits
). This third-party class also uses a __metaclass__
.
So what's the right way of managing two metaclasses? Should my metaclass be a subclass of Enthought's metaclass? Or should I just invoke Enthought's metaclass inside my metaclass's __new__
method to get the type object that I will return? Or is there some other mystical incantation to use in this particular circumstance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信这实际上是你唯一的选择。如果派生类的元类不是其所有基类的元类的子类,那么当您尝试创建派生类时,Python 将抛出 TypeError。因此,
PythonDirectPublic
的元类应该类似于如果您无权访问第三方基类的元类的定义,则可以将
BaseMetaClass
替换为 <代码>enthought.traits.api.HasTraits.__metaclass__。虽然很啰嗦,但它会起作用。I believe that is in fact your only choice. If the metaclass of a derived class is not a subclass of the metaclasses of all of its bases then Python will throw a TypeError when you try to create the derived class. So your metaclass for
PythonDirectPublic
should look something likeIf you don't have access to the definition of the metaclass for your third-party base class, you can replace
BaseMetaClass
withenthought.traits.api.HasTraits.__metaclass__
. It's wordy, but it will work.您可以递归地使用 PythonDirectPublic.subclasses() 的结果,而不是添加另一个元类。
Rather than adding another metaclass, you could recursively use the result of PythonDirectPublic.subclasses().