简体   繁体   中英

Dynamic multiple inheritance in Python

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM