Section 2. Chapitre 5
single
Challenge: Building a Plugin Interface
Glissez pour afficher le menu
You are building a plugin system for a data export tool. Plugins are registered with a central registry and must conform to a standard interface. Your task is to implement the ABC, two concrete plugins, and a virtual subclass registration.
You are given the following third-party class that you cannot modify:
class LegacyXmlExporter:
def export(self, data):
items = "".join(f"<item>{row}</item>" for row in data)
return f"<root>{items}</root>"
def get_format(self):
return "XML"
Tâche
Glissez pour commencer à coder
- Import
ABCandabstractmethodfromabc. - Define
ExporterPlugin(ABC)with two abstract methods:export(self, data)– takes a list and returns a string;get_format(self)– returns the format name as a string.
- Add a
__subclasshook__classmethod toExporterPluginthat returnsTrueif the subclass has bothexportandget_formatin its MRO, otherwise returnsNotImplemented. - Define
MarkdownExporter(ExporterPlugin)that:- implements
export(self, data)– returns a markdown list where each item indatais prefixed with"- ", joined by newlines; - implements
get_format(self)that returns"Markdown".
- implements
- Register
LegacyXmlExporteras a virtual subclass ofExporterPluginusingregister(). - Create instances:
md_exporter = MarkdownExporter()andxml_exporter = LegacyXmlExporter(). - Store
isinstance(md_exporter, ExporterPlugin)inmd_is_pluginandisinstance(xml_exporter, ExporterPlugin)inxml_is_plugin. - Print both variables.
Solution
Tout était clair ?
Merci pour vos commentaires !
Section 2. Chapitre 5
single
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion