Dynamic multiple inheritance in Python

两盒软妹~` 提交于 2019-12-25 01:13:19

问题


I'm having a combination of "backend" together with a "type".

Backends: Cloudant, ElasticSearch, File, ZODB

Types: News, (potentially others)

So I'm now defining classes like:

Plugin
PluginCloudant (which inherits from Plugin)
PluginNews (which inherits from Plugin)

The combined class is then:

class PluginCloudantNews(PluginCloudant, PluginNews)

Now, I'd like to dynamically allow people to define a Service (which takes a Plugin as an argument).

The service's implementation will only rely on the backend, so it seems like that part of the class should automatically be used.

My point is, I shouldn't have to give PluginCloudantNews as argument to the service (since the Cloudant part is a logical consequence of being in the Cloudant service), so rather the less specific PluginNews.

How can I just pass PluginNews to the Service class (the type), but still end up with the PluginCloudantNews functionality?

Some kind of dynamic inheritance...

It should glue together PluginCloudant with class PluginNews, or other type, which are all defined upfront.


回答1:


I'm not sure I have fully understood your question, however you can "dynamically" construct class objects using the type builtin. The following two lines produce the same result:

class PluginCloudantNews(PluginCloudant, PluginNews): pass

PluginCloudantNews = type('PluginCloudantNews', (PluginCloudant, PluginNews), {})

As you can see, type() takes three arguments: the name of the new class, a list of base classes to inherit from, a dictionary with the attributes to add to the new class.



来源:https://stackoverflow.com/questions/32104219/dynamic-multiple-inheritance-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!